我编写了一个用于下载excel文件的代码。文件内容源自数据库。代码在本地计算机上工作但在服务器上部署时。下载时Excel文件被破坏。我无法在代码中找到问题。请帮我摆脱这个问题。第一种导出excel的方法和第二种在excelsheet中编写内容的方法。第二种方法是通过第一种方法调用的。
public static void doGetExportException(String sheetId, ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws ServletException, IOException
{
HttpServletResponse response = PortalUtil.getHttpServletResponse(resourceResponse);
try
{
long maxSheetId = Long.parseLong(sheetId);
System.out.println("maxSheetId="+maxSheetId);
List<Customer_Exception> lstCustomer_Exceptions =UploadExcelUtil.getCustomerExceptions(maxSheetId);
XSSFWorkbook outPutSheet= writeExcelsheet(lstCustomer_Exceptions);
ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
outPutSheet.write(outByteStream);
byte [] outArray = outByteStream.toByteArray();
String fileName = "Download_"+new Date(new java.util.Date().getTime())+".xlsx";
response.setContentType("application/ms-excel; charset=UTF-8");
response.setContentLength(outArray.length);
response.setHeader("Expires:", "0");
response.addHeader(HttpHeaders.CACHE_CONTROL, "max-age=3600, must-revalidate");
response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+fileName);
response.addHeader(HttpHeaders.CONTENT_ENCODING, "Binary");
OutputStream outStream = response.getOutputStream();
outStream.write(outArray);
outStream.flush();
outStream.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static XSSFWorkbook writeExcelsheet(List<Customer_Exception> lstCustomer_Exceptions) {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Exceptions");
CellStyle styleHeader = workbook.createCellStyle();
XSSFFont fontHeader = workbook.createFont();
XSSFColor color = new XSSFColor(Color.BLACK);
fontHeader.setColor(color);
fontHeader.setBold(true);
fontHeader.setFontHeight(13);
styleHeader.setFont(fontHeader);
sheet.createFreezePane(0, 1);
CellStyle styleData = workbook.createCellStyle();
XSSFFont fontData = workbook.createFont();
fontData.setColor(color);
fontData.setFontHeight(12);
styleData.setFont(fontData);
int rownum = 0;
XSSFRow rowHeader = sheet.createRow(rownum++);
List<String> lstCellHeaders =getCellHeaders();
int cellnum = 0;
for(String cellHeader:lstCellHeaders){
XSSFCell cell = rowHeader.createCell(cellnum++);
cell.setCellStyle(styleHeader);
cell.setCellValue((String)cellHeader);
}
for (Customer_Exception customer_Exception:lstCustomer_Exceptions) {
List<String> lstCellValues =getCellValues(customer_Exception);
XSSFRow rowData = sheet.createRow(rownum++);
cellnum = 0;
for(String cellValue:lstCellValues){
XSSFCell cell = rowData.createCell(cellnum++);
cell.setCellStyle(styleData);
cell.setCellValue((String)cellValue);
}
}
return workbook;
}
答案 0 :(得分:0)
对于.xlsx,您应使用ContentType:“application / vnd.openxmlformats-officedocument.spreadsheetml.sheet”。 这解决了我的问题。