please see this is my coding about to write .xlsx file it is working but i can't open file after wrote. it says file is corrupted. please give solution
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.getCe开发者_如何学JAVAllFormula();
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();
}
}
}
}
You appear to be creating a workbook, populating it, then creating a new empty one and saving that! Try removing the line
XSSFWorkbook newWorkBook = new XSSFWorkbook();
And then change the write to be a write from workBook rather than newWorkBook and you should be fine.
精彩评论