java - 无法写入 Excel 文件 (Apache POI)
问题描述
public static String already_exists(ArrayList<String> reg_id, ArrayList<String> doc_id, ArrayList<String> status) throws RowsExceededException, WriteException, IOException{
WritableWorkbook myFirstWbook = null;
FileOutputStream out = new FileOutputStream(new File("C://Users//Desktop//OP_demo.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Java Books");
int rowCount = 0;
int columnCount = 0;
for(int i=0;i<reg_id.size();i++)
{
Object[][] bookData={{reg_id.get(i),doc_id.get(i),status.get(i)}};
Row row = sheet.createRow(rowCount++);
//System.out.println(reg_id.get(i)+doc_id.get(i)+status.get(i));
for (Object[] aBook : bookData)
{
for (Object field : aBook)
{
org.apache.poi.ss.usermodel.Cell cell = row.createCell(columnCount++);
{
cell.setCellValue(field.toString());
}
}
workbook.write(out);
}
}
out.close();
return "";
}
以上是我用来写入 Excel 文件“OP_Demo”的代码片段。必须使用 arraylists reg_id、doc_id 和 status 的值来填充单元格。但是,当我运行程序时,只有索引位置 0 处的列表值被写入文件。我是否在 for 循环中放错了特定语句?
解决方案
您需要将 workbook.write(out); 移到循环之外。workbook.write(out); 将工作簿的内容写入文件流,一旦处理完所有记录,您就需要写入文件,否则每次执行时文件的内容都会被覆盖。
public static String already_exists(ArrayList<String> reg_id, ArrayList<String> doc_id, ArrayList<String> status) throws RowsExceededException, WriteException, IOException{
WritableWorkbook myFirstWbook = null;
FileOutputStream out = new FileOutputStream(new File("C://Users//Desktop//OP_demo.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Java Books");
int rowCount = 0;
int columnCount = 0;
for(int i=0;i<reg_id.size();i++)
{
Object[][] bookData={{reg_id.get(i),doc_id.get(i),status.get(i)}};
Row row = sheet.createRow(rowCount++);
//System.out.println(reg_id.get(i)+doc_id.get(i)+status.get(i));
for (Object[] aBook : bookData)
{
for (Object field : aBook)
{
org.apache.poi.ss.usermodel.Cell cell = row.createCell(columnCount++);
{
cell.setCellValue(field.toString());
}
}
}
}
workbook.write(out); // writing the workbook to file-stream outside loop
out.close();
return "";
}
您可以参考以下链接:https ://www.mkyong.com/java/apache-poi-reading-and-writing-excel-file-in-java/ 它显示了使用读写 excel 文件的基本示例阿帕奇兴趣点。
推荐阅读
- javascript - 试图通过单击清除按钮清除所有客户。在删除客户时也删除客户
- azure - 当 Azure APP 服务位于 NGINX 等反向代理后面时,如何更改 MSAL 回复 URL?
- shell - 我正在尝试在目录中查找文件,但 shell 代码片段未检测到它
- python - 'dict' 对象在 add_coupon 中没有属性 'coupon' ecommerce/store/views.py,第 254 行
- amazon-web-services - 如何从 Cloud Formation 迁移到 Terraform?
- reactjs - 当数据来自 redux 存储时,useState() 在刷新时丢失状态(数据)
- bash - 监控日志文件尾部是否有字符串,如果没有找到,退出
- json - 如何从配置单元 SQL 表描述生成 json 对象?
- javascript - 每个项目的更新计数(附加片段)
- maven - 在执行 pom.xml 作为 maven 测试时没有测试运行,但在执行 testng.xml 时它工作正常