我需要追加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
任何想法???