java - 如何使用 JFileChooser 保存 XLS 文件?
问题描述
我有负责使用 Apache POI 工作簿创建 XLS 文件的方法,我想使用JFileChooser
. 现在我可以使用文件编写器创建该文件并将其保存到预定义的位置。
但要求是使用 保存该文件JFileChooser
,我无法理解如何执行此操作。
这是我的代码:
public void excelFileCreation()
{
try
{
String path = "D:/";
String fileName = "EwayBill.xls";
String filename = path.concat(fileName);
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("Eway Bill");
Row row1 = sheet.createRow((short)0);
Row row2 = sheet.createRow((short)0);
CellRangeAddress transactionDetails = new CellRangeAddress(0, 0, 0, 5);
sheet.addMergedRegion(transactionDetails);
row2.createCell(0).setCellValue("Transaction details");
CellRangeAddress fromConsignorDetails = new CellRangeAddress(0, 0, 6, 13);
sheet.addMergedRegion(fromConsignorDetails);
row2.createCell(6).setCellValue("Transaction details");
Row rowhead = sheet.createRow((short)1);
rowhead.createCell(0).setCellValue("User GSTIN");
rowhead.createCell(1).setCellValue("Supply Type");
rowhead.createCell(2).setCellValue("Sub Type");
rowhead.createCell(3).setCellValue("Document Type");
rowhead.createCell(4).setCellValue("Document No");
Row row = sheet.createRow((short)2);
row.createCell(0).setCellValue(" ");
row.createCell(1).setCellValue(" ");
row.createCell(2).setCellValue(" ");
row.createCell(3).setCellValue(" ");
row.createCell(4).setCellValue(" ");
for(int i=0; i<=79; i++)
{
sheet.setColumnWidth(i, 6000);
}
FileOutputStream fileOut = new FileOutputStream(filename);
wb.write(fileOut);
fileOut.close();
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
{
java.io.File file = fileChooser.getSelectedFile();
// save to file
}
System.out.println("Your excel file has been generated!");
}
catch(Exception e)
{
e.printStackTrace();
}
}
解决方案
答案最有可能改变这一点:
FileOutputStream fileOut = new FileOutputStream(filename);
wb.write(fileOut);
fileOut.close();
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
{
java.io.File file = fileChooser.getSelectedFile();
// save to file
}
对此:
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
{
java.io.File file = fileChooser.getSelectedFile();
FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut);
fileOut.close();
}
我说“最有可能”是因为我无法确定是否会看到 MCVE / SSCCE。
推荐阅读
- java - 这段代码在哪里失败?两种方法之间的区别
- flutter - 如何使用scrollDirection设置gridview项目的宽度和高度:Axis.horizontal?
- python - 如何使用 itertools.groupby 将 CSV 数据转换为字典
- python - 水平合并两个 DataFrame 而不重新索引第一个
- node.js - Node JS / 生成 PDF 服务器端
- facebook - 如何使用 facebook 营销 api 创建多个广告集
- angular - 类型'可观察的
' 必须有一个返回迭代器的 '[Symbol.iterator]()' 方法 - angular - 将属性添加到对象 [Typescript] 的正确方法是什么
- flutter - 在 TextFormField Flutter 中聚焦时如何清空提示文本
- python - 在python3中查找文件