我正在寫一個應用程序,它從Microsoft Access數據庫讀取數據並將此數據寫入Excel工作表。一切正常,但不是將新數據寫入文件。這裏是代碼:用apache poi從Java寫入Excel文件
private static XSSFWorkbook readFile(String filename) throws IOException {
// return new XSSFWorkbook(new FileInputStream(filename));
InputStream inp = new FileInputStream(filename);
XSSFWorkbook wb = null;
try {
wb = (XSSFWorkbook) WorkbookFactory.create(inp);
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return wb;
}
public void writeToFile(LinkedList<TimeRowWrapper> list) {
try {
// read file
XSSFWorkbook workbook = readFile(fileName);
// choose table from index
XSSFSheet sheet = workbook.getSheetAt(kapaSheetIndex);
for (Row row : sheet) {
int rowNum = row.getRowNum();
// iterate over list for row id
for (TimeRowWrapper trw : list) {
if (rowNum == trw.getRowNumber()) {
double hour = Math
.round(trw.getTotalTime()/60.0 * 100.)/100.;
Cell cell = row.getCell(timeCol);
cell.setCellValue(hour);
}
}
}
XSSFFormulaEvaluator.evaluateAllFormulaCells(workbook);
FileOutputStream out = new FileOutputStream(fileName);
workbook.write(out);
out.close();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
如果條件不成立? – Jayan 2012-03-31 10:45:22
您的Excel表格是否已包含要寫入的行和列?如果沒有,調用getRow()和getCell()將無處可去,因爲它們將返回null。或者因爲您依賴HSSFSheet的Iterable接口,我認爲它將有零迭代。嘗試迭代你的模型列表,並調用createRow()和createCell()。 – nansen 2012-03-31 10:49:37
if條件成立。一切工作正常在每個循環。 Excel文件包含我想要寫入數據的行和列。 – krains 2012-03-31 11:20:53