Java的Apache的POI打开文件? [英] Java Apache POI Opening file?
问题描述
我有一个编辑现有的excel文件,并将其保存为一个新文件的Java程序。不过,我也想在程序结束时自动打开新创建的文件。是否有一个Apache POI的命令,让我做到这一点?
I have a Java program that edits an existing excel file and saves it as a new file. However, I would also like the program to automatically open the newly created file upon ending. Is there an apache poi command that lets me do this?
推荐答案
由于您没有提供code,我米使用的的 ViralPatel教程
As you have not Provided Code , I m using the Example of ViralPatel Tutorial
让我们创建Excel文件首先
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
Map<String, Object[]> data = new HashMap<String, Object[]>();
data.put("1", new Object[] { "Emp No.", "Name", "Salary" });
data.put("2", new Object[] { 1d, "John", 1500000d });
data.put("3", new Object[] { 2d, "Sam", 800000d });
data.put("4", new Object[] { 3d, "Dean", 700000d });
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object[] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if (obj instanceof Date)
cell.setCellValue((Date) obj);
else if (obj instanceof Boolean)
cell.setCellValue((Boolean) obj);
else if (obj instanceof String)
cell.setCellValue((String) obj);
else if (obj instanceof Double)
cell.setCellValue((Double) obj);
}
}
try {
FileOutputStream out = new FileOutputStream(new File("D:\\new.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
/** Opening Excel File From Java **/
try {
Desktop.getDesktop().open(new File("D:\\new.xls"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
输出
解决方案:将这个code。与try / catch块你已经创建的Excel后,用正确的位置,它会自动打开
Solution : Put this code with Try/Catch Block after You have created Excel with correct Location, It will be opened Automatically
Desktop.getDesktop()开(新文件(D:\\ new.xls));
否则U可以调用此以及
尝试使用Desktop.open()而不是Desktop.edit():
Try to use Desktop.open() instead of Desktop.edit() :
Desktop dt = Desktop.getDesktop();
dt.open(new File("D:\\new.xls"));
如果Desktop.open()不可用,则在Windows文件关联可用于:
If Desktop.open() is not available then the Windows file association can be used :
Process p = Runtime.getRuntime() .exec("rundll32
url.dll,FileProtocolHandler " + "D:\\new.xls");
这篇关于Java的Apache的POI打开文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!