我有一个Web项目,从数据库中显示网格视图。 Arraylist名称是leadSchoolList。所以,我保留了一个按钮,当点击它时,它会在Struts动作类中运行一个方法(名为:-actionExportToExcel)。现在我可以将列表元素导出到excel。
但是我面临的问题是打开导出excel Sheet的窗口。因此在actionExportToExcel中调用另一个方法(名为:-open)。但我不知道我哪里错了,所以有人可以帮助我吗?
public String actionExportToExcel(){
try {
FileOutputStream fileOut = new FileOutputStream("D:/poi-test.xls");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
leadSchoolList = leadSchoolService.getAllLeadSchool();
for(int rowNum = 0; rowNum < leadSchoolList.size(); rowNum++){
HSSFRow row = sheet.createRow(rowNum);
//for(int colNum = 0; colNum < 5; colNum++ ){
HSSFCell cell1 = row.createCell(0);
LeadSchool leadSchool = leadSchoolList.get(rowNum);
cell1.setCellValue(leadSchool.getLeadSchool_String_LSchool_ID());
HSSFCell cell2 = row.createCell(1);
cell2.setCellValue(leadSchool.getLeadSchool_String_Name());
HSSFCell cell3 = row.createCell(2);
cell3.setCellValue(leadSchool.getLeadSchool_String_Address());
HSSFCell cell4 = row.createCell(3);
cell4.setCellValue(leadSchool.getLeadSchool_String_Phone_No());
HSSFCell cell5 = row.createCell(4);
cell5.setCellValue(leadSchool.getLeadSchool_String_Remarks());
System.out.println("Successfully exported to Excel");
}
try {
wb.write(fileOut);
// fileOut.flush();
open(fileOut);
//fileOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
addActionError("The process cannot access the file because it is being used by another process");
e.printStackTrace();
}
return SUCCESS;
}
private void open(FileOutputStream f) {
String[] cmd = new String[4];
try{
cmd[0] = "cmd.exe";
cmd[1] = "/C";
cmd[2] = "start";
cmd[3] = "D:/poi-test.xls";
Runtime.getRuntime().exec(cmd);
//Runtime.getRuntime().exec("cmd.exe /c start D:/poi-test.xls");
System.out.print("file opened");
}
catch(Exception e){
e.printStackTrace();
}
}
答案 0 :(得分:3)
幸运的是我自己找到了解决方案。首先需要运行flush()和close()方法,然后运行第二个(命名:-open)方法。在open方法中,而不是R
Runtime.getRuntime().exec(cmd);
我把它扩展为两行: -
Runtime run = Runtime.getRuntime();
Run.exec(cmd);
多数民众赞成......:D