poi導出Excel直接在瀏覽器下載

需求:導出成Excel格式,要在瀏覽器看到相似於下載的效果。java

導出的Excel和下載在同一個目錄下。ajax

xxController.java apache

// 導出
@RequestMapping(value = "/createExcelToDisk", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
public @ResponseBody String createExcelToDisk(HttpServletResponse response,List<Object>valueList,) throws IOException, IllegalAccessException, ClassNotFoundException {
        response.reset(); // 清除buffer緩存
        // 指定下載的文件名
        response.setHeader("Content-Disposition", "attachment;filename=contacts" + CurrentTime.getDateTime() + ".xlsx");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        XSSFWorkbook workbook = null;
        try {
            workbook = ExcelUtils.exportContacts(valueList);
            OutputStream output;
            try {
                output = response.getOutputStream();
                BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
                bufferedOutPut.flush();
                workbook.write(bufferedOutPut);
                bufferedOutPut.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return null;
    }
ExcelUtils.java 
package com.ky.lm.util.common;

import java.util.List;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtils {

    public static XSSFWorkbook exportContacts(List<Object> valueList)
            throws IllegalArgumentException, IllegalAccessException, ClassNotFoundException {
        XSSFWorkbook xssfWorkbook = null;
        String sheetName = "客戶列表";
        xssfWorkbook = createExcelFile(valueList, sheetName);
        return xssfWorkbook;
    }

    public static XSSFWorkbook createExcelFile(List<Object> valueList, String sheetName)
            throws IllegalArgumentException, IllegalAccessException, ClassNotFoundException {
        // 建立新的Excel工做簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 在Excel工做簿中建一工做表,其名爲缺省值, 也能夠指定Sheet名稱
        XSSFSheet sheet = workbook.createSheet(sheetName);
        XSSFRow row = sheet.createRow(0);
        XSSFCell cell = row.createCell(0);
        cell.setCellValue("姓名");
        cell = row.createCell(1);
        cell.setCellValue("年齡");
        for (int i = 0; i < valueList.size(); i++) {
            row = sheet.createRow((int) i + 1);
                        row.createCell(i).setCellValue(valueList[i]);
        }
        return workbook;
    }

}

效果json

 

這裏補充一個要點:導出直接在瀏覽器下載這樣的格式    !!不支持ajax!!  最好用a標籤來寫。瀏覽器

 

有什麼不明白的能夠在評論裏提問哦 ^ - ^ !緩存

相關文章
相關標籤/搜索