简体   繁体   English

在Excel工作表的列末尾写入Excel数据

[英]Write excel data in end of column in the Excel Sheet

I want to add value in the end of the column and but if i run the class it overrides the excel 我想在列的末尾添加值,但是如果我运行该类,它将覆盖excel

JAVA , Apache POI: 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();
    }

The Excel overrides every time and new data alone is added. 每次都将覆盖Excel,并且仅添加新数据。 Note : If both the ID's are same , we need to add the second map data in the same row 注意:如果两个ID都相同,我们需要在同一行中添加第二个地图数据

The reason why your document is replaced every time is that your workbook is blank. 每次都替换文档的原因是您的workbook为空白。 workbook.write(out) means you write everything in the workbook to a location (extract.xlsx), not that you write the data of your workbook into a file! workbook.write(out)意味着您将工作簿中的所有内容都写入一个位置(extract.xlsx),而不是将工作簿中的数据写入文件中!

What you should be doing is open the workbook you're trying to edit: 您应该做的是打开您要编辑的工作簿:

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

... get the last row or column ...获取最后一行或最后一列

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

... and write your data from there. ...然后从那里写入数据。 Then, as before, you can use workbook.write(out) to save your workbook. 然后,像以前一样,您可以使用workbook.write(out)保存您的工作簿。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM