I'm converting CSV file to XLS file.
When I do the conversion, everything works perfect; however, when there's a comma inside the cell, it separates a column into two columns.
EX:
| Hello, World! | CSV FILE |
after conversion
| Hello | World! | CSV FILE | X --- What I get currently
| Hello, World! | CSV FILE | O --- What I want
String ab = thisLine.replaceAll(", ", " ");
Assuming everyone uses space after using a comma, replaceAll would work but this is not an ideal solution.
public void csv2excel(String csv) throws Exception
{
String inputCSVFile = csv + ".csv";
ArrayList arList=null;
ArrayList al=null;
String fName = inputCSVFile;
String thisLine;
int count=0;
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis);
int i=0;
arList = new ArrayList();
while ((thisLine = myInput.readLine()) != null)
{
al = new ArrayList();
//String ab = thisLine.replaceAll(", ", " ");
//String strar[] ab.split(",");
String strar[] = thisLine.split(",");
//Here is where I split the columns.
for(int j=0;j<strar.length;j++)
{
al.add(strar[j]);
}
arList.add(al);
i++;
}
try
{
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
for(int k=0;k<arList.size();k++)
{
ArrayList ardata = (ArrayList)arList.get(k);
HSSFRow row = sheet.createRow((short) 0+k);
for(int p=0;p<ardata.size();p++)
{
HSSFCell cell = row.createCell((short) p);
String data = ardata.get(p).toString();
if(data.startsWith("=")){
cell.setCellType(CellType.STRING);
data=data.replaceAll("\"", "");
data=data.replaceAll("=", "");
cell.setCellValue(data);
}else if(data.startsWith("\"")){
data=data.replaceAll("\"", "");
cell.setCellType(CellType.STRING);
cell.setCellValue(data);
}else{
data=data.replaceAll("\"", "");
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(data);
}
//*/
// cell.setCellValue(ardata.get(p).toString());
}
}
FileOutputStream fileOut = new FileOutputStream(csv + ".xls");
hwb.write(fileOut);
fileOut.close();
} catch ( Exception ex ) {
ex.printStackTrace();
}
myInput.close();
fis.close();
}
I wonder if there's just a way to split column by column.
public void csv2excel(String csv) throws Exception
{
String inputCSVFile = csv + ".csv";
ArrayList arList=null;
ArrayList al=null;
String fName = inputCSVFile;
String thisLine;
int count=0;
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis);
int i=0;
arList = new ArrayList();
while ((thisLine = myInput.readLine()) != null)
{
al = new ArrayList();
StringBuilder myLine = new StringBuilder(thisLine);
int lineLength = thisLine.length();
int bool = 0;
for (int k = 0; k < lineLength; k++)
{
if (thisLine.charAt(k) == '"')
{
bool++;
}
else if (thisLine.charAt(k) == ',' && bool % 2 != 0)
{
myLine.setCharAt(k, ' ');
}
}
//System.out.println(myLine);
//String ab = thisLine.replaceAll(", ", " ");
String strar[] = myLine.toString().split(",");
for(int j=0;j<strar.length;j++)
{
al.add(strar[j]);
}
arList.add(al);
i++;
}
try
{
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
for(int k=0;k<arList.size();k++)
{
ArrayList ardata = (ArrayList)arList.get(k);
HSSFRow row = sheet.createRow((short) 0+k);
for(int p=0;p<ardata.size();p++)
{
HSSFCell cell = row.createCell((short) p);
String data = ardata.get(p).toString();
if(data.startsWith("=")){
cell.setCellType(CellType.STRING);
data=data.replaceAll("\"", "");
data=data.replaceAll("=", "");
cell.setCellValue(data);
}else if(data.startsWith("\"")){
data=data.replaceAll("\"", "");
cell.setCellType(CellType.STRING);
cell.setCellValue(data);
}else{
data=data.replaceAll("\"", "");
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(data);
}
//*/
// cell.setCellValue(ardata.get(p).toString());
}
}
FileOutputStream fileOut = new FileOutputStream(csv + ".xls");
hwb.write(fileOut);
fileOut.close();
} catch ( Exception ex ) {
ex.printStackTrace();
}
myInput.close();
fis.close();
}
I coded to work around it...
Looks ugly, but works...
Would like to know if anyone has better answer.
Related
I have the following method, but this one has a problem and it is that in a part of the file there are some special characters where the character with hexadecimal value 81(.) when the program generates the export of the file is 3F(?) and with that it damages the binary:
public static void exportbinary() {
List<String> files = listFiles(source,1);
System.out.println("Reviewing files to extract data");
String registro = null;
String contenido = "";
for (String s : files) {
//The name of the files to be processed is adjusted
String ogName=s;
System.out.println("Renaming files to extract binary data...");
File sFile = new File(source, s);
sFile.renameTo(new File(source,s+"ext"));
s = s+"ext";
//Start binary extraction process
File sourceFile = new File(source, s);
File destFile = new File(destination, ogName);
if (destFile.exists()) {
destFile.delete();
}
if (!dctmp.exists()) {
try {
dctmp.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Writer w = null;
try {
w = new BufferedWriter(new FileWriter(dctmp, true));
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("Processing" + sourceFile + " en " + destFile);
try (BufferedReader br = new BufferedReader(new FileReader(sourceFile))) {
String data;
while ((data = br.readLine()) != null) {
String line = data;
if (line.substring(0, 6).equals("924007")) {
// Valores binarios
String binarios = line.substring(585, 586 + 82);
line = line.substring(0, 585) + (new String(new char[83]).replace('\0', '0'))
+ line.substring((586 + 82), line.length());
// TID
String TID = line.substring(1005, 1020);
registro = TID + ";" + binarios + "\n";
contenido = contenido + registro;
}
BufferedWriter wrtr = new BufferedWriter(new FileWriter(destFile, true));
wrtr.append(line + "\n");
wrtr.close();
line = null;
}
System.out.println("Data is added to the temporary");
w.append(contenido);
w.close();
br.close();
System.out.println("Successfully complete process");
} catch (Exception e) {
e.printStackTrace();
} finally {
sourceFile.delete();
}
}
}
I did an exercise treating the file with FileInputStream() and it worked and kept the value, and it is the following code:
private void testBinary(File filename) {
try {
FileInputStream FileOrigin = new FileInputStream(filename);
// Arrays
byte[] biyeFile = new byte[(int) filename.length()];
int[] intArray = new int[biyeFile.length];
char[] CharArrayBit = new char[intArray.length];
FileOrigin.read(biyeFile);
for (int i = 0; i < biyeFile.length; i++) {
// Converting each char into its byte equivalent
intArray[i] = (int) Byte.toUnsignedInt(biyeFile[i]);
}
File temp = new File("C:/MOVIMIENTO/ebcdic/ascii/", filename.getName() + ".TMP");
temp.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(temp);
for (int j = 0; j < charArrayBit.length; ++j) {
charArrayBit[j] = (char) intArray[j];
try {
if ((intArray[j] != 10) && (intArray[j] != 13)) {
fileOutputStream.write(charArrayBit[j]);
}
} catch (IOException e) {
e.printStackTrace();
}
}
FileOrigin.close();
fileOutputStream.close();
filename.delete();
temp.renameTo(filename);
} catch (IOException e) {
e.printStackTrace();
}
}
But I can't seem to implement the logic I made with the one that is already there and I'm getting stuck :( on how I can deal line by line in bytes. Try this Java - Read line using InputStream
The mess I have is that by using String I already lose the value String data; data = br.readLine() String line = data;
Update:
The idea is that the temporary file where I am printing the TID and binary is as follows:
file dc.tmp
200232133:..3....¢...€ . ...
300232133:.....Þù...€ ....€
400232133:ù....Þù...€ ....€ ....
etc
This is some VB.net code that I'm basing on pulling out the binary:
While POS < inputFile.Length
While reg < rowlen
dato1 = inputFile.ReadByte()
POS = POS + 1
reg = reg + 1
dato11 = BitConverter.GetBytes(dato1)
If (binary = 1 And (reg > 589 And reg <= 589 + 53 + 53)) Then
' here you should read two bytes and convert it to one
byte1 = dato1
' now read the second byte
byte2 = inputFile.ReadByte()
reg = reg + 1
POS = POS + 1
final = CInt("&H" & (Chr(byte1) + Chr(byte2)))
Else
dato2 = Encoding.Convert(source, DEST, dato11)
final = dato2(0)
End If
Print(1, Chr(final))
If (reg < 7) Then 'the first positions give us the type of message
MTI = MTI + Chr(dato1)
End If
If reg = 7 Then
binary = 0
rowlen = 1400
If (MTI = "924007") Then ' binary
binary = 1
rowlen = 1400 + 53
End If
MTI = ""
End If
End While
POS = POS + 2
reg = 0
End While
Thank you.
I want to read data from a CSV file in Java and then put this data into a list. The data in the CSV is put into rows which looks like:
Data, 32, 4.3
Month, May2, May 5
The code I have currently only prints the [32].
ArrayList<String> myList = new ArrayList<String>();
Scanner scanner = new Scanner(new File("\\C:\\Users\\Book1.csv\\"));
scanner.useDelimiter(",");
while(scanner.hasNext()){
myList.add(scanner.next());
for (int i = 0; i <= myList.size(); i++) {
System.out.println(myList.toString());
}
scanner.close();
}
Maybe this code can help you, maybe this code is different from yours, you use arrayList while I use regular array.
Example of the data:
Farhan,3.84,4,72
Rajab,2.98,4,72
Agil,2.72,4,72
Alpin,3.11,4,73
Mono,3,6,118 K
imel,3.97,7,132
Rano,2.12,6,110
Kukuh,4,1,22
Placing data on each row in a csv file separated by commas into the array of each index
int tmp = 0;
String read;
Mahasiswa[] mhs = new Mahasiswa[100];
BufferedWriter outs;
BufferedReader ins;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Scanner input = new Scanner(System.in);
try {
ins = new BufferedReader(new FileReader("src/file.csv"));
tmp = 0;
while ((read = ins.readLine()) != null) {
String[] siswa = read.split(",");
mhs[tmp] = new Mahasiswa();
mhs[tmp].nama = siswa[0];
mhs[tmp].ipk = Float.parseFloat(siswa[1]);
mhs[tmp].sem = Integer.parseInt(siswa[2]);
mhs[tmp].sks = Integer.parseInt(siswa[3]);
tmp++;
i++;
}
ins.close();
} catch (IOException e) {
System.out.println("Terdapat Masalah: " + e);
}
Print the array data
tmp = 0;
while (tmp < i) {
System.out.println(mhs[tmp].nama + "\t\t" +
mhs[tmp].ipk + "\t\t" +
mhs[tmp].sem + "\t\t" +
mhs[tmp].sks);
tmp++;
}
ArrayList<String> myList = new ArrayList<String>();
try (Scanner scanner = new Scanner(new File("C:\\Users\\Book1.csv"))) {
//here at your code there are backslashes at front and end of the path that was the
//main reason you are not able to read csv file
scanner.useDelimiter(",");
while (scanner.hasNext()) {
myList.add(scanner.next());
}
for (int i = 0; i < myList.size(); i++) { //remember index is always equal to "length - 1"
System.out.println(myList);
}
} catch (Exception e) {
e.printStackTrace();
}
you also did not handle the FileNotFoundException
Hope this helps:)
I have to convert CSV to XLS format through Java POI since I am doing some manipulations with XLS sheets through POI. Below is my code:
File file = new File("C:\\abc.csv");
FileInputStream fin = null;
fin = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(fin);
HSSFSheet firstSheet1 = workbook.getSheetAt(0);
Now I want to write a fuctions, lets say method name is convertcsvtoexcel which will accept the file obj and in return it will be give me converted XLS file that file will be stored in my C: drive with the name abcout.xls and later on I will be passing it to workbook as shown. I have tried the following code. Please advise how I can custoise it to make it fittable for my piece of code.
ArrayList arList = null;
ArrayList al = null;
String fName = "test.csv";
String thisLine;
int count = 0;
FileInputStream file = null;
file = new FileInputStream(new File("C:\\abc.csv"));
//FileInputStream fis = new FileInputStream(file);
DataInputStream myInput = new DataInputStream(file);
int i = 0;
arList = new ArrayList();
while ((thisLine = myInput.readLine()) != null) {
al = new ArrayList();
String strar[] = thisLine.split(",");
for (int j = 0; j < strar.length; j++) {
al.add(strar[j]);
}
arList.add(al);
System.out.println();
i++;
}
try {
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
for (int k = 0; k < arList.size(); k++) {
ArrayList ardata = (ArrayList) arList.get(k);
HSSFRow row = sheet.createRow((short) 0 + k);
for (int p = 0; p < ardata.size(); p++) {
HSSFCell cell = row.createCell((short) p);
String data = ardata.get(p).toString();
if (data.startsWith("=")) {
cell.setCellType(Cell.CELL_TYPE_STRING);
data = data.replaceAll("\"", "");
data = data.replaceAll("=", "");
cell.setCellValue(data);
} else if (data.startsWith("\"")) {
data = data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(data);
} else {
data = data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(data);
}
//*/
// cell.setCellValue(ardata.get(p).toString());
}
System.out.println();
}
FileOutputStream fileOut = new FileOutputStream("C:\\abcout.xls");
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated");
} catch (Exception ex) {
ex.printStackTrace();
} //main method end
public static void csvToXLSX() {
try {
String csvFileAddress = "test.csv"; //csv file address
String xlsxFileAddress = "test.xlsx"; //xlsx file address
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.createSheet("sheet1");
String currentLine=null;
int RowNum=0;
BufferedReader br = new BufferedReader(new FileReader(csvFileAddress));
while ((currentLine = br.readLine()) != null) {
String str[] = currentLine.split(",");
RowNum++;
XSSFRow currentRow=sheet.createRow(RowNum);
for(int i=0;i<str.length;i++){
currentRow.createCell(i).setCellValue(str[i]);
}
}
FileOutputStream fileOutputStream = new FileOutputStream(xlsxFileAddress);
workBook.write(fileOutputStream);
fileOutputStream.close();
System.out.println("Done");
} catch (Exception ex) {
System.out.println(ex.getMessage()+"Exception in try");
}
}
I'm creating a program that aims to take in n number of splits and split a file into that amount of sub-files. In my SplitFile.java, I'm reading a file, passing an array of substrings that show the text that's supposed to go in each split file. I then convert the string into a byte array and write the byte array to the split file, but each file I'm creating is outputting something just slightly different.
SplitFile.java
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
public class SplitFile
{
int numberOfSplits = 1;
File file;
String[] parts = new String[5];
public SplitFile(File file,int numberOfSplits)
{
this.file = file;
this.numberOfSplits = numberOfSplits;
}
public void FileSplitter() throws IOException
{
FileInputStream fis = new FileInputStream(file);
String fileText = readFile();
if(numberOfSplits == 2)
{
int mid = fileText.length() / 2;
parts[0] = fileText.substring(0, mid);
parts[1] = fileText.substring(mid);
}
else if(numberOfSplits == 3)
{
int third = fileText.length() / 3;
int secondThird = third + third;
parts[0] = fileText.substring(0, third);
parts[1] = fileText.substring(third, secondThird);
parts[2] = fileText.substring(secondThird);
}
for(int i = 1; i <= numberOfSplits; i++)
{
BufferedInputStream bis = new BufferedInputStream(new fileInputStream(file));
FileOutputStream out;
String name = file.getName();
byte[] b = parts[i - 1].getBytes(Charset.forName("UTF-8"));
int temp = 0;
while((temp = bis.read(b)) > 0);
{
File newFile = new File(name + " " + i + ".txt");
newFile.createNewFile();
out = new FileOutputStream(newFile);
out.write(b, 0, temp); // Writes to the file
out.close();
temp = 0;
}
}
}
public String readFile() throws IOException
{
BufferedReader br = new BufferedReader(new FileReader(file));
try
{
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null)
{
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
}
finally
{
br.close();
}
}
}
If I pass in 2 as the amount of splits I want, it is not splitting it right at the middle, with file 1 being the first half and file 2 being the second half, and instead giving the end of the text file for both files. My problem seems to be here:
while((temp = bis.read(b)) > 0);
{
File newFile = new File(name + " " + i + ".txt");
newFile.createNewFile();
out = new FileOutputStream(newFile);
out.write(b, 0, temp); // Writes to the file
out.close();
temp = 0;
}
An example file I'll use on here is this file:
myFile.txt
abcdefghijklmnopqrstuvwxyz
It splits into two files that go as follows:
myFile.txt 1
nopqrstuvqxyz
myFile.txt 2
opqrstuvqxyz
Any idea on what the problem is?
In your code, you define File newFile = new File(name + " " + i + ".txt"); and out = new FileOutputStream(newFile); in whilte loop, it's not correct.
while((temp = bis.read(b)) > 0); not semicolon here =.="
Many mistake in your code
I will change your code like:
File newFile = new File(name + " " + i + ".txt");
newFile.createNewFile();
out = new FileOutputStream(newFile);
out.write(b); // Writes to the file
out.flush();
out.close();
If you need your code run as you want, here you are
for (int i = 1; i <= numberOfSplits; i++) {
String name = file.getName();
byte[] b = parts[i - 1].getBytes(Charset.forName("UTF-8"));
ByteArrayInputStream bis = new ByteArrayInputStream(b);
int temp = 0;
File newFile = new File(name + " " + i + ".txt");
newFile.createNewFile();
FileOutputStream out = new FileOutputStream(newFile);
while ((temp = bis.read()) > 0)
{
out.write(temp); // Writes to the file
}
out.flush();
out.close();
}
i have a document excel with textboxes
i want to create in this textboxes a text from java code
this is the code to get value , how i'm going to edit it using poid apache
try {
FileInputStream fsIP = new FileInputStream(new File("C:\\Book1.xls"));
// InputStream input = new FileInputStream("Book1.xls");
POIFSFileSystem fs = new POIFSFileSystem(fsIP);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFPatriarch pat = sheet.getDrawingPatriarch();
List children = pat.getChildren();
Iterator it = children.iterator();
while (it.hasNext()) {
HSSFShape shape = (HSSFShape) it.next();
if (shape instanceof HSSFTextbox) {
shape.getAnchor()
HSSFTextbox textbox = (HSSFTextbox) shape;
HSSFRichTextString richString = textbox.getString();
String str = richString.getString();
System.out.println("String: " + str);
System.out.println("String length: " + str.length());
}
}
} catch (IOException ex) {
ex.printStackTrace();
}