2011-04-27 63 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和你應該罰款。