gpt4 book ai didi

java - 将Excel数据写入Excel工作表的列末尾

转载 作者:行者123 更新时间:2023-12-02 01:27:25 25 4
gpt4 key购买 nike

我想在列的末尾添加值,但如果我运行该类,它会覆盖 Excel

JAVA、Apache POI:

    // Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
// Create a blank sheet
XSSFSheet sheet = workbook.createSheet("MyPolicies");
// Iterate over data and write to sheet
Set<Integer> keyset = data.keySet();
int rownum = 0;
for (Integer key : keyset) {
// this creates a new row in the sheet
Row row = sheet.createRow(rownum++);
Object[] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {

// this line creates a cell in the next column of that row
Cell cell = row.createCell(cellnum++);
if (obj instanceof String) {
cell.setCellValue((String) obj);
}

else if (obj instanceof Integer)
cell.setCellValue((Integer) obj);
}
}
try {
// this Writes the workbook
FileOutputStream out = new FileOutputStream(new File("extract.xlsx"));
workbook.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}

Excel 每次都会覆盖并仅添加新数据。注意:如果两个ID相同,我们需要在同一行添加第二个 map 数据

最佳答案

您的文档每次都被替换的原因是您的工作簿是空白的。 workbook.write(out) 表示将工作簿中的所有内容写入某个位置(extract.xlsx),而不是将工作簿的数据写入文件!

您应该做的是打开您要编辑的工作簿:

FileInputStream xlsFile = new FileInputStream("extract.xls");
XSSFWorkbook workbook = new XSSFWorkbook(xlsFile);

...获取最后一行或最后一列

XSSFSheet sheet = workbook.getSheetAt(0);
int lastRow = sheet.getLastRowNum();

...并从那里写入您的数据。然后,像以前一样,您可以使用 workbook.write(out) 保存工作簿。

关于java - 将Excel数据写入Excel工作表的列末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56689733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com