Java – 追加excel

我需要追加excel。 我写代码:

import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.sql.ResultSet; import java.sql.Statement; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import javafx.collections.FXCollections; import javafx.collections.ObservableList; public class AppendExcel { public static void main(String[] args) throws Exception { String excelFilePath = "append.xlsx"; try { FileInputStream inputStream = new FileInputStream(new File(excelFilePath)); Workbook workbook = WorkbookFactory.create(inputStream); Sheet sheet = workbook.getSheetAt(0); DbManagerSQL test = new DbManagerSQL(); String sql = "select distinct Code,Item,Description from MyTable"; Statement stmt = test.dbConnect().createStatement(); ResultSet rs = stmt.executeQuery(sql); int rowCount = sheet.getLastRowNum(); while (rs.next()) { Row row = sheet.createRow(++rowCount); int columnCount = 0; Cell cell = row.createCell(columnCount); cell.setCellValue(rowCount); cell = row.createCell(++columnCount); cell.setCellValue((String) rs.getString(1)); cell.setCellValue((String) rs.getString(2)); cell.setCellValue((String) rs.getString(3)); } inputStream.close(); FileOutputStream outputStream = new FileOutputStream("append.xlsx"); workbook.write(outputStream); // workbook.close(); outputStream.close(); } catch (IOException | EncryptedDocumentException | InvalidFormatException ex) { ex.printStackTrace(); } } } 

我的Excel有专栏

在这里输入图像说明

但是当我追加Excel时,我接下来了

在这里输入图像说明

它看起来像只记得最后一列。 我认为这个箴言是在这行代码中

cell = row.createCell(++ columnCount);

但我现在不是如何添加数据来获得像这样的excel

在这里输入图像说明

任何想法???

为每个条目创build一个单元格:

 int columnCount = 0; Cell cell = row.createCell(columnCount); cell.setCellValue(rowCount); columnCount++; cell = row.createCell(columnCount); cell.setCellValue((String) rs.getString(1)); columnCount++; cell = row.createCell(columnCount); cell.setCellValue((String) rs.getString(2)); columnCount++; cell = row.createCell(columnCount); cell.setCellValue((String) rs.getString(3)); 

你在这个时候增加你的columnCount:

 int columnCount = 0; cell = row.createCell(++columnCount); 

所以你总是写在同一个单元格。 你必须把错误的初始化。