我可以编写前X行,但是当我尝试编写另外X行时,我会遇到异常 -
org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException:无法保存:保存包时发生错误:部件/docProps/app.xml无法使用marshaller org.apache.poi保存在流中。 openxml4j.opc.internal.marshallers.DefaultMarshaller@6825c828
public class ExcellTest
{
XSSFWorkbook workbook;
XSSFSheet sheet;
int rowNum = 0;
String excellFileName = "";
FileOutputStream fileOut;
public ExcellTest(String excellFileName) {
createExcellSheet("test");
this.excellFileName = excellFileName;
}
public void createExcellSheet(String sheetName) {
workbook = new XSSFWorkbook();
sheet = workbook.createSheet(sheetName);
}
public void addData() {
Row rowMsg = sheet.createRow((short)rowNum);
rowNum++;
Cell cell;
for (int i = 0; i < 200; i++) {
cell = rowMsg.createCell(i);
cell.setCellValue(rowNum);
}
}
public void createExcellFile() {
try {
fileOut = new FileOutputStream(new File (excellFileName));//, true);
}
catch (IOException e) {
System.out.print("Cant write workbook into file: " + excellFileName);
}
}
public void writeExcellSheet() {
// write workbook into file
try {
workbook.write(fileOut);
} catch (FileNotFoundException e) {
System.out.print("Cant create file: " + excellFileName);
} catch (IOException e) {
System.out.print("Cant write workbook into file: " + excellFileName);
}
}
public void closeFile() {
try {
fileOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
ExcellTest excellTest = new ExcellTest("C:\\TestJavaBinary\\1.xlsx");
excellTest.createExcellFile();
// write 2 rows
excellTest.addData();
excellTest.addData();
excellTest.writeExcellSheet();
// write 2 additional rows
excellTest.addData();
excellTest.addData();
// THE NEXT LINE WILL THROW EXCEPTION
excellTest.writeExcellSheet();
excellTest.closeFile();
}
我只能将行写入xlsx
文件一次,因为第二次尝试会抛出异常:
Exception in thread "main" org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException: Fail to save: an error occurs while saving the package : The part /docProps/app.xml fail to be saved in the stream with marshaller org.apache.poi.openxml4j.opc.internal.marshallers.DefaultMarshaller@6825c828
at org.apache.poi.openxml4j.opc.ZipPackage.saveImpl(ZipPackage.java:503)
at org.apache.poi.openxml4j.opc.OPCPackage.save(OPCPackage.java:1425)
at org.apache.poi.POIXMLDocument.write(POIXMLDocument.java:201)
at mainPkg.ExcellTest.writeExcellSheet(ExcellTest.java:58)
at mainPkg.Main.main(Main.java:23)
Caused by: org.apache.poi.openxml4j.exceptions.OpenXML4JException: The part /docProps/app.xml fail to be saved in the stream with marshaller org.apache.poi.openxml4j.opc.internal.marshallers.DefaultMarshaller@6825c828
at org.apache.poi.openxml4j.opc.ZipPackage.saveImpl(ZipPackage.java:494)