2011-04-27 65 views
0

请看这是我编写的.xlsx文件的编码,它正在工作,但写完后我无法打开文件。它说文件已损坏。请给解决方案如何使用apache poi编写.xlsx文件

OPCPackage fileSystems = OPCPackage.open(file.getAbsolutePath(),PackageAccess.READ); 

XSSFWorkbook workBook = new XSSFWorkbook(fileSystems); 
XSSFSheet sheet = workBook.getSheetAt(0); 
Iterator rows = sheet.rowIterator(); 

while (rows.hasNext()) 
{ 
XSSFRow row = (XSSFRow) rows.next(); 

System.out.println ("Row No.: " + row.getRowNum()); 

Iterator cells = row.cellIterator(); 

while (cells.hasNext()) 
{ 
XSSFCell cell = (XSSFCell) cells.next(); 

String value = "OldValue"; 
if(value.equals(cell.getStringCellValue())) 
{ 
switch (cell.getCellType()) 
{ 
case Cell.CELL_TYPE_NUMERIC: 
double cellNumericValue = cell.getNumericCellValue(); 
cell.setCellValue(cellNumericValue); 
break; 
case Cell.CELL_TYPE_STRING: 
String cellStringValue = cell.getStringCellValue(); 
cell.setCellValue("NewValue"); 
break; 
case Cell.CELL_TYPE_FORMULA: 
String cellFormulaValue = cell.getCellFormula(); 
cell.setCellValue(cellFormulaValue); 
break; 
case Cell.CELL_TYPE_BLANK: 
cell.setCellValue(""); 
break; 
case Cell.CELL_TYPE_BOOLEAN: 
boolean cellBooleanValue = cell.getBooleanCellValue(); 
cellBooleanValue=false; 
cell.setCellValue(cellBooleanValue); 
break; 
case Cell.CELL_TYPE_ERROR: 
byte error = cell.getErrorCellValue(); 
cell.setCellValue(error); 
break; 
default: 
break; 
} 
} 
} 
} 
XSSFWorkbook newWorkBook = new XSSFWorkbook(); 
FileOutputStream outPutStream = null; 
try { 
outPutStream = new FileOutputStream(file); 
newWorkBook.write(outPutStream); 
} catch (IOException e) { 
e.printStackTrace(); 
} finally { 
if (outPutStream != null) { 
try { 
outPutStream.flush(); 
outPutStream.close(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
} 
} 

回答

3

您似乎正在创建工作簿,填充它,然后创建一个新的空的并保存!尝试删除线

XSSFWorkbook newWorkBook = new XSSFWorkbook(); 

,然后更改写是写从工作簿而不是newWorkBook和你应该罚款。