Excel file gets corrupted when i change the value

2019-09-07 03:56发布

问题:

I'm trying to read and Xslx file using JAVA POI, edit it and save it. But when i change any cell value on row#0 (Header) the output file gets corrupted.

Excel can recover the file by repairing, Table from /xl/tables/table.xm .

    FileInputStream file = new FileInputStream("inventorywithbin431.xlsx");
    XSSFWorkbook workbook = (XSSFWorkbook) WorkbookFactory.create(file);
    XSSFSheet rawdata = workbook.getSheetAt(0);

    String[] headers = new String[] { "ItemCodeNoFRU","Company","ItemCode","ItemName","ItemGroup","PartNumber","Warehouse","Segment","Bin","WareHouseQty","OnOrder","IsCommited","BinQty","Cost","BinExtCost"};

    //Set Header
    for(int i=0;i<14;i++)
        rawdata.getRow(0).getCell(i).setCellValue(headers[i]);

    file.close();
    //write changes
    try ( 
        FileOutputStream output_file = new FileOutputStream("inventorywithbin431.xlsx")) {
        workbook.write(output_file);
        output_file.flush();
        output_file.close();
    }