我是用下面的代碼編寫的,用於下載xls或xlsx。我可以下載xls或xlsx文件,但它說文件已損壞。 有人來幫我處理這種錯誤如何使用apache POI下載xls或xlsx文件
public static void writeUploadErrorDetailsToExcel(List<OfflineRegistrationBean> userErrorList,
HttpServletResponse response, String uploadedfileName)
{
Workbook workbook = null;
response.reset();
if (StringUtils.hasText(uploadedfileName) && uploadedfileName.contains(".xlsx"))
{
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
workbook = new XSSFWorkbook();
}
else
{
response.setContentType("application/vnd.ms-excel");
workbook = new HSSFWorkbook();
}
Sheet offlineErrorMsg = workbook.createSheet("offlineLeads_error");
int rowIndex = 0;
if (userErrorList != null && userErrorList.size() > 0)
{
String sheeHead[] = IConstants.SHEET_HEADING.split("##");
for (int i = 0; i < sheeHead.length; i++)
{
Row row = offlineErrorMsg.createRow(rowIndex++);
row.createCell(i).setCellValue(sheeHead[i]);
}
for (OfflineRegistrationBean registrationBean : userErrorList)
{
Row row = offlineErrorMsg.createRow(rowIndex++);
int cellIndex = 0;
row.createCell(cellIndex++).setCellValue(registrationBean.getFirstName());
row.createCell(cellIndex++).setCellValue(registrationBean.getLastName());
row.createCell(cellIndex++).setCellValue(registrationBean.getEmail());
row.createCell(cellIndex++).setCellValue(registrationBean.getPhoneNo());
row.createCell(cellIndex++).setCellValue(registrationBean.getStudyLevel());
row.createCell(cellIndex++).setCellValue(registrationBean.getYearValue());
row.createCell(cellIndex++).setCellValue(registrationBean.getOffice());
row.createCell(cellIndex++).setCellValue(registrationBean.getErrorMessage());
}
try
{
response.setHeader("content-disposition", "attachment; filename="+uploadedfileName);
OutputStream outObject = response.getOutputStream();
workbook.write(outObject);
outObject.flush();
outObject.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}