2011-04-27 9 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 쓰기로 쓰기를 변경 당신도 잘해야합니다.

관련 문제