1. 程式人生 > >springMvc生成匯出excel檔案

springMvc生成匯出excel檔案

/**
 * 匯出商品excel表格
 * @throws UnsupportedEncodingException 
 */
@RequestMapping(value = "/exceptProduct", method = RequestMethod.GET)
public void exceptProduct(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {

HSSFWorkbook wb = new HSSFWorkbook();//建立一個excel表格
request.setCharacterEncoding("utf-8");

response.setCharacterEncoding("utf-8");
response.setContentType("application/x-download");

String fileName = "商品表.xls";
fileName = URLEncoder.encode(fileName, "ISO8859-1");
response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
HSSFSheet sheet = wb.createSheet("商品表"); //新建工作表

sheet.setDefaultRowHeight((short) (2 * 256));//設定寬
sheet.setColumnWidth(0, 50 * 160);//高
HSSFFont font = wb.createFont();
font.setFontName("宋體");//字型
font.setFontHeightInPoints((short) 16);
HSSFRow row = sheet.createRow((int) 0);
sheet.createRow((int) 1);//第一列
sheet.createRow((int) 2);//第二列

HSSFCellStyle style = wb.createCellStyle();

style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

HSSFCell cell = row.createCell(0);
cell.setCellValue("編號 ");
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue("商品名稱 ");
cell.setCellStyle(style);

 List<Product> list = productService.findAll();//獲取所有商品

for (int i = 0; i < list.size(); i++)//迴圈插入
{
HSSFRow row1 = sheet.createRow((int) i + 1);
Product product = list.get(i);
row1.createCell(1).setCellValue(product.getSn());//編號
row1.createCell(0).setCellValue(product.getName());//名稱
}
try
{
OutputStream out = response.getOutputStream();
wb.write(out);
out.close();
}
        catch (IOException e)  
        {  
            e.printStackTrace();  
        }

}



之前用的ajax請求後臺地址,一直沒法下載,前臺頁面彈不出下載框
問題原因:
那是因為response原因,一般請求瀏覽器是會處理伺服器輸出的response,例如生成png、檔案下載等,然而ajax請求只是個“字元型”的請求,json,text,html,xml,即請求的內容是以文字型別存放的。檔案的下載是以二進位制形式進行的,雖然可以讀取到返回的response,但只是讀取而已,是無法執行的,說白點就是js無法呼叫到瀏覽器的下載處理機制和程式。
解決方案:
    隱藏表單,用提交表單的形式
    用window.open() 或 window.location.href()
    建立iframe,iframe的src可以是檔案地址url來請求後臺並下載檔案