尝试将xlsx文件导出到本地可以正常工作,但是将其部署到服务器(使用unix命令)后无法正常工作。
当我打开excel时,出现错误,因为“由于扩展名无效,excel无法打开文件”
下面是导出xlsx的代码:
public String getXLSXWriter(ResultSet rs, String file_name)
{
String filepath="";
try {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(file_name);
XSSFRow rowhead = sheet.createRow((int) 0);
filepath=prop.getProperty("file_store_path")+file_name+timeStamp+".xlsx";
FileOutputStream fileOut = new FileOutputStream(filepath);
rowhead.createCell((int) 0).setCellValue("id");
rowhead.createCell((int) 1).setCellValue("name");
int i = 1;
while (rs.next()){
XSSFRow row = sheet.createRow((int) i);
row.createCell((int) 0).setCellValue(rs.getString("id"));
row.createCell((int) 1).setCellValue(rs.getString("domain_id"));
row.createCell((int) 2).setCellValue(rs.getString("name") );
i++;
}
workbook.write(fileOut);
fileOut.close();
System.out.println("XLSX done!!");
} catch (SQLException e1) {
e1.printStackTrace();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return filepath;
}
public void getDownloaded(String filepath,HttpServletResponse response)
{
try {
File file=new File(filepath);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename="+file.getName());
FileInputStream in=new FileInputStream(file);
ServletOutputStream out=response.getOutputStream();
byte[] outputByte = new byte[4096];
//copy binary content to output stream
int length;
while((length=in.read(outputByte, 0, 4096)) != -1){
out.write(outputByte, 0, length);
}
in.close();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}