[英]how to write data on existing xls or xlsx file using apache POI in android
我尝试使用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();
}
}
}
尝试file.close(); 在workbook.write(outFile);之后 outFile.close();
我认为这里的问题是你试图得到一个行和一个不是首先创建的单元格。
在调用cell = sheet.getRow(row);
之前,您需要先创建一个Row
cell = sheet.getRow(row);
喜欢
XSSFRow row = sheet.createRow(rowIndex);
并创建一个Cell
,以及像
Cell cell = row.createCell(cellIndex);
查看完整的示例以获取更多详细信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.