Java只打印最后一个数据单元

我正在尝试从csv读取内容并将其打印到excel文件中。 到目前为止,我有这个,但是它只打印出csv的最后一个值到excel文件的第一个单元格中。 我尝试使用列和行的增量,但我得到一个空指针exception错误。

int i=0; int j=0; int k=0; int row=68; int column=0; String [] part={"052","064"}; try{ //InputStream inp = new FileInputStream(); //Workbook wb = WorkbookFactory.create(inp); Workbook wb = WorkbookFactory.create(new File("30_results_w_graphs.xls")); for (k=0; k<part.length; k++) { Sheet sheet = wb.getSheet(part[k]); Cell cell = null; Scanner scanner = new Scanner(new File(part[k]+".csv")); scanner.useDelimiter(","); while(scanner.hasNext()){ cell=sheet.getRow(row).getCell(column); cell.setCellValue(scanner.next()); //row++; //column++; } FileOutputStream fileOut = new FileOutputStream("30_results_U_w_graphs.xls"); wb.write(fileOut); scanner.close(); } } 

我相信这是一个嵌套的for循环增加行和列,但即使在常规增量我得到一个空指针exception。

我不知道你想要做什么,但是这段代码展示了使用Apache POI将CSV文件读入现有Excel文件的一些基本步骤。 现有的工作表/行/单元不会被删除。

CSV文件看起来像这样:

 12,14,18,21 82,19,18,44 9,4,31,12 

将文件读入以文件名命名的表格中:

  File excel = new File("/tmp/result.xls"); //Open existing Excel file: Workbook wb = WorkbookFactory.create(excel); //Create a new Excel file: //Workbook wb = new HSSFWorkbook(); //Read in CSV String name = "test"; Sheet sheet = wb.getSheet(name); if (sheet == null) { sheet = wb.createSheet(name); } int rowCount = 0; Scanner scanner = new Scanner(new File("/tmp/" + name + ".csv")); while (scanner.hasNextLine()) { String[] rowData = scanner.nextLine().split(","); for (int col = 0; col < rowData.length; col++) { Row row = sheet.getRow(rowCount); if (row == null) row = sheet.createRow(rowCount); Cell cell = row.getCell(col); if (cell == null) { cell = row.createCell(col); } cell.setCellValue(rowData[col]); } rowCount++; } wb.write(new FileOutputStream(excel)); } 

你不增加rowcolumn 。 使用createRow(int row)createCell(int column)创build新的单元格。