Home » excel » excel – csv to xls with more then 65536 lines in java

excel – csv to xls with more then 65536 lines in java

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a java program which reads in a csv file and converts it into a xls file:

String file2 = "myFile.csv";
FileInputStream fis2 = new FileInputStream(file2);
DataInputStream myInput2 = new DataInputStream(fis2);
String thisLine;
arList = new ArrayList();
while ((thisLine = myInput2.readLine()) != null) {
al = new ArrayList();
String strar[] = thisLine.split(",");
for (int j = 0; j < strar.length; j++) {
       al.add(strar[j]);
}
arList.add(al);
i++;
}

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);
    cell.setCellValue(ardata.get(p).toString());
     }
}

FileOutputStream fileOut = new FileOutputStream(file2.replace("csv", "xls"));
hwb.write(fileOut);
fileOut.close();
myInput2.close();
fis2.close();

However, I have a CSV with more then 65536 lines and thus above code is resulting in error.

What could I do to above code to handle csv’s with more then 65536 lines.

Thanks for reading!

How to&Answers:

You problem is probably in the HSSFSheet class. In the this line

HSSFRow row = sheet.createRow((short) 0 + k)

You are calling a method with short argument. The short type is only 2 bytes long so, the class can store only up to 65,535 rows.

If you have access to the class, you can refactor it, to use int or even long.

Answer:

I assume the problem is in the ArrayList you are using to store your CSV file. Try using a Reader to process your CSV file a line at a time rather than reading the whole thing at once.

Answer:

Dont cast the index to a short in your call to CreateRow. Shorts are limited to a max value of 65535.