天天看點

JAVA 通過POI 模版,導出excel

 如有不足,歡迎指正,謝謝 !

1、Maven引入  POI jar包、模版和結果檔案.rar下載下傳

<dependency>

  <groupId>org.apache.poi</groupId>

  <artifactId>poi</artifactId>

  <version>4.0.1</version>

</dependency>

<dependency>

  <groupId>net.sf.jxls</groupId>

  <artifactId>jxls-core</artifactId>

  <version>1.0.4</version>

</dependency>

2、工具方法如下:

package com.***.***.***;      
import net.sf.jxls.transformer.XLSTransformer;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;      
CLASS 省略。。。

/**
     *
     * @param request
     * @param response
     * @param tempPath 模版的相對路徑
     * @param resultMap 結果集
     * @throws Exception
     */
    public static void excelTempExport(HttpServletRequest request,HttpServletResponse response,String tempPath, Map resultMap) {
        String tempFileName = null;
        String newFileName = null;
        File newFile = null;
        XLSTransformer transformer = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //獲得模版
            tempFileName = request.getSession().getServletContext().getRealPath(tempPath);
            //新的檔案名稱
            newFileName= new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            //檔案名稱統一編碼格式
            newFileName = URLEncoder.encode(newFileName, "utf-8");
            //生成的導出檔案
            newFile = File.createTempFile(newFileName, ".xls");
            //transformer轉到Excel
            transformer = new XLSTransformer();
            //将資料添加到模版中生成新的檔案
            transformer.transformXLS(tempFileName, resultMap, newFile.getAbsolutePath());
            //将檔案輸入
            InputStream inputStream = new FileInputStream(newFile);
            // 設定response參數,可以打開下載下傳頁面
            response.reset();
            //設定響應文本格式
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + String.valueOf((newFileName + ".xls").getBytes(), "iso-8859-1"));
            //将檔案輸出到頁面
            ServletOutputStream out = response.getOutputStream();
            bis = new BufferedInputStream(inputStream);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // 根據讀取并寫入
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //使用完成後關閉流
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {}
        }
    }

//測試類       
@RequestMapping(value = "/exportExcelTest", method = RequestMethod.GET)
public void exportExcelTest(HttpServletRequest request, HttpServletResponse response) {
    Map map = new HashMap(4);
    Map itemMap = null;
    //商戶
    List<Map> merchantList = new ArrayList<Map>();
    itemMap = new HashMap();
    itemMap.put("id", 3);
    itemMap.put("merchant_name", "張3");
    itemMap.put("market_id", 1);
    itemMap.put("market_name", "市場1");
    merchantList.add(itemMap);
    itemMap = new HashMap();
    itemMap.put("id", 4);
    itemMap.put("merchant_name", "張5");
    itemMap.put("market_id", 2);
    itemMap.put("market_name", "市場2");
    merchantList.add(itemMap);
    map.put("merchantList", merchantList);

    //品類
    List<Map> bccList = new ArrayList<Map>();
    itemMap = new HashMap();
    itemMap.put("id", 1);
    itemMap.put("category", "蘋果");
    itemMap.put("sub_category", "紅富士蘋果");
    bccList.add(itemMap);
    itemMap = new HashMap();
    itemMap.put("id", 2);
    itemMap.put("category", "蘋果");
    itemMap.put("sub_category", "國光蘋果");
    bccList.add(itemMap);
    map.put("bccList", bccList);

    //供貨商
    List<Map> merchantSupplierList = new ArrayList<Map>();
    itemMap = new HashMap();
    itemMap.put("id", 1);
    itemMap.put("supplierName", "李四");
    itemMap.put("supplierShopName", "李四水果店");
    merchantSupplierList.add(itemMap);
    itemMap = new HashMap();
    itemMap.put("id", 2);
    itemMap.put("supplierName", "王五");
    itemMap.put("supplierShopName", "王五蔬菜店");
    merchantSupplierList.add(itemMap);
    map.put("merchantSupplierList", merchantSupplierList);

    //省市區
    List<Map> areaList = new ArrayList<Map>();
    itemMap = new HashMap();
    itemMap.put("sheng_id", 610000);
    itemMap.put("sheng_name", "陝西省");
    itemMap.put("shi_id", 610100);
    itemMap.put("shi_name", "西安市");
    itemMap.put("qu_id", 610104);
    itemMap.put("qu_name", "蓮湖區");
    areaList.add(itemMap);
    itemMap = new HashMap();
    itemMap.put("sheng_id", 610000);
    itemMap.put("sheng_name", "陝西省");
    itemMap.put("shi_id", 610100);
    itemMap.put("shi_name", "西安市");
    itemMap.put("qu_id", 610113);
    itemMap.put("qu_name", "雁塔區");
    areaList.add(itemMap);
    map.put("areaList", areaList);
    ExcelTemplate.exportExcelByTemplate(request, response, map, "excelTemplate/template.xls");
}      

 3、導出成功後結果如圖:

JAVA 通過POI 模版,導出excel