我们:write to xlsm (Excel 2007) using apache poi
当我向文件写一个简单的字符串时,我无法打开该文件。错误 - " 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();
}
答案 0 :(得分: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();
}