我尝试使用apache POI将数据放入模板.xls文件(如果需要,可以是xlsx),但我无法弄明白,文件仍然保持不变。 PrintStackTrace中没有抛出任何异常。你能告诉我一个工作代码吗?我读了这么多文件所以请帮我处理工作代码。感谢
我的代码:
final Button but = (Button) findViewById(R.id.bk);
but.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
writeXLSFile(3, 3);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
public static void writeXLSFile(int row, int col) throws IOException {
try {
FileInputStream file = new FileInputStream(Environment.getExternalStorageDirectory().toString() +"telegran/"+ "ex.xls");
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Cell cell = null;
//Update the value of cell
cell = sheet.getRow(row).getCell(col);
cell.setCellValue("changed");
file.close();
FileOutputStream outFile =new FileOutputStream(new File(Environment.getExternalStorageDirectory().toString() +"telegran/"+ "ex.xls"));
workbook.write(outFile);
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
尝试file.close();在workbook.write之后(outFile); outFile.close();
答案 1 :(得分:0)
我认为这里的问题是你试图得到一个行和一个不是首先创建的单元格
在调用Row
之前,您需要先创建cell = sheet.getRow(row);
,如
XSSFRow row = sheet.createRow(rowIndex);
并创建Cell
以及
Cell cell = row.createCell(cellIndex);
有关详细信息,请参阅此full example