写入excel文件时会丢失一些数据。 Java的

我创buildXLSX文件并添加到单元格的一些值,它写道,一切正常,但是当我读回文件或只是打开文件。 我没有看到所有的数据。

File myfile = new File("hello.xlsx"); Workbook workBook = new XSSFWorkbook(); Sheet sheet = workBook.createSheet("sheet"); String[] tokens= {"A1", "B5", "C7", "J1", "K15", "Z20"}; for (String tok: tokens) { CellReference ref = new CellReference(tok); Row row = sheet.createRow(ref.getRow()); Cell cell = row.createCell((short) ref.getCol()); cell.setCellValue("blabla"); System.out.println(ref); } workBook.write(new FileOutputStream(myfile)); workBook.close(); System.out.println(); FileInputStream fileInputStream = new FileInputStream(myfile); Workbook workBook2 = new XSSFWorkbook(fileInputStream); Sheet worksheet = workBook2.getSheet("sheet"); for(String tok: tokens) { CellReference ref= new CellReference(tok); Row row = worksheet.getRow(ref.getRow()); Cell cell = row.getCell(ref.getCol()); if(cell != null){ System.out.println(ref); } } 

但是当我读回他们,我只得到他们几个。 为什么?

 org.apache.poi.ss.util.CellReference [A1] org.apache.poi.ss.util.CellReference [B5] org.apache.poi.ss.util.CellReference [C7] org.apache.poi.ss.util.CellReference [J1] org.apache.poi.ss.util.CellReference [K15] org.apache.poi.ss.util.CellReference [Z20] org.apache.poi.ss.util.CellReference [B5] org.apache.poi.ss.util.CellReference [C7] org.apache.poi.ss.util.CellReference [J1] org.apache.poi.ss.util.CellReference [K15] org.apache.poi.ss.util.CellReference [Z20] 

您正在创buildRow 1(索引0)两次:

 ... Row row = sheet.createRow(ref.getRow()); ... 

如果ref引用A1 ,则会创build一个新的第0行,如果ref引用J1 ,则会再次创build新的第0行。 两次都创build一个新的空行0。 所以在这一行中第一个创build的单元格将会丢失。

在创build新行之前,您必须检查行是否已经存在:

 ... Row row = sheet.getRow(ref.getRow()); if (row == null) row = sheet.createRow(ref.getRow()); ... 

看到这个链接:

http://poi.apache.org/apidocs/org/apache/poi/POIXMLDocument.html#close%28%29

从write()的文档中:

“把这个文档写到OutputStream中,注意 – 如果文档是从File而不是InputStream打开的,那么你必须写出一个不同的文件,通过OutputStream覆盖是不可能的。