【问题标题】:csv to xls with more then 65536 lines in javacsv到xls在java中超过65536行
【发布时间】:2012-03-01 11:05:51
【问题描述】:

我有一个 java 程序,它读取一个 csv 文件并将其转换为一个 xls 文件:

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();

但是,我有一个超过 65536 行的 CSV,因此上面的代码会导致错误。

我可以对上面的代码做些什么来处理超过 65536 行的 csv。

感谢阅读!

【问题讨论】:

  • Excel 允许的最大值不是 65536 吗?如果您无法将额外的行加载到 Excel 中,那么进行转换就没有什么意义了...?
  • 65536 是一个旧限制,现在增加了!
  • 好的 - 我显然是在一个仍然有限制的史前版本;-)

标签: java excel csv xls


【解决方案1】:

您的问题可能出在 HSSFSheet 类中。在这一行

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

您正在使用短参数调用方法。 short 类型只有 2 个字节长,因此该类最多只能存储 65,535 行。

如果你可以访问这个类,你可以重构它,使用 int 甚至 long。

【讨论】:

  • 正确。早些时候的 createRow 只是短暂的。但现在该方法也采用整数!谢谢!
【解决方案2】:

我认为问题出在您用来存储 CSV 文件的 ArrayList 中。尝试使用阅读器一次处理您的 CSV 文件一行,而不是一次读取整个文件。

【讨论】:

    【解决方案3】:

    在调用 CreateRow 时不要将索引转换为短。短裤的最大值限制为 65535。

    【讨论】:

      猜你喜欢
      • 2012-02-16
      • 1970-01-01
      • 2014-08-19
      • 1970-01-01
      • 1970-01-01
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多