使用Apache POI附加Excel文件

我有一个java程序打印1000个整数值,每个我运行它。 我想在每次运行程序时将输出复制到excel文件。 我想输出Excel文件第一列中的第一次运行,然后在同一个Excel文件中的后续列中复制下一次运行。 例如:

运行:1 value1 value2。 。 value1000运行:2 value1 value2。 。 value1000我想要第一个输出在Excel文件的第一列,第二个输出在第二列

这是我的代码:

int rownum=1; int cellnum=1; File file; HSSFWorkbook workbook; HSSFSheet sheet; HSSFRow row; HSSFCell cell; HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Sample sheet"); public void writeOutput(double meandispersion) { String dispersion = Double.toString(meandispersion); HSSFRow row = sheet.createRow(rownum++); HSSFCell cell = row.createCell(cellnum); cell.setCellValue("dispersion"); try { FileOutputStream out = new FileOutputStream("newFile.xls"); workbook.write(out); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } 

在主代码中总共有1000个时间步,在每个时间步中调用这个方法,并将meand分散的值传递给它。 它在第一列1000行中打印1000个值。 问题是,当我第二次运行该程序时,我想复制第二列中的1000个值,第三个第三列等等。 目前它不附加值,它覆盖整个文件。 任何人都可以指出这个问题吗?

您必须读取现有文件,将自己的新输出附加到现有数据(在正确的列中,然后将其写入文件。

现在你根本没有读取文件,这会覆盖现有的内容。

希望这可以帮助。

POI的快速指南 (又名“繁忙的开发人员指南HSSF和XSSFfunction”)包含大量代码片断,其中包括讨论打开现有工作簿,读取和写入并保存修改后的工作簿(从该页面逐字复制的示例,添加一些评论):

 InputStream inp = new FileInputStream("workbook.xls"); // notice how the Workbook must be constructed from the existing file Workbook wb = WorkbookFactory.create(inp); // Navigating in POI always follows the same logic: // 1. grab a sheet // 2. grab a row from that sheet // 3. grab a cell from that row Sheet sheet = wb.getSheetAt(0); Row row = sheet.getRow(2); Cell cell = row.getCell(3); // a condition like the one that follows will be needed to know in what column // you have to write your data: if (cell == null) cell = row.createCell(3); cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue("a test"); // Write the output to a file FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut); fileOut.close(); 

那个,那个页面上的其他例子应该让你快速加速。