-1

wef :使用 apache poi 写入 xlsm (Excel 2007)

当我将一个简单的字符串写入文件时,我无法打开文件。错误 - “Excel 无法打开文件 'Test1.xlsm',因为文件格式或文件扩展名无效”

try {

    Workbook workbook;
    workbook = new XSSFWorkbook(OPCPackage.open("C:\\temp\\Test.xlsm"));

    String content = "This is the text content";
    byte[] contentInBytes = content.getBytes();

    FileOutputStream out = new FileOutputStream("C:\\temp\\Test1.xlsm");
    out.write(contentInBytes);

    workbook.write(out);
    out.close(); 

    System.out.println("xlsm created successfully..");
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (InvalidFormatException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
4

1 回答 1

0

我必须使用 FileInputStream 来读取和 FileOutputStream 来写入。它就像一个魅力!将记录集写入 xlsm

   try {
        File file = new File("C://temp//test.xslm");
        FileInputStream inputStream = new FileInputStream(file);
        Workbook wb = new XSSFWorkbook(OPCPackage.open(inputStream));

        Sheet sheet = wb.getSheet("Sheet1");
        for (int x = 1; x < 5; x++) {
            for (int y = 0; y < 4; y++) {
                Cell c = sheet.getRow(x).getCell(y);
                c.setCellValue(recs.getValueAt(x - 1, y).toString());
            }
        }

        FileOutputStream fileOut = new FileOutputStream("C://temp//test.xslm");
        wb.write(fileOut);
        fileOut.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (InvalidFormatException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
于 2016-09-12T21:00:16.130 回答