1. 程式人生 > >工具類——簡單匯出excel

工具類——簡單匯出excel

環境:spring+mvc+mybatis+maven

工具類:

import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class ExportExcel {
    /**
     * <p class="detail">
     * 功能:簡單匯出excel
     * </p>
     * @author zhaoyang
     * @date 2017年6月16日
     * @param sheetName sheet名稱
     * @param head excel第一行單元格名稱
     * @param list 實體類資料
     * @param path 下載路徑
     */
    public static void outExcel(String sheetName,String[] head,List<Map<String,Object>> list,String path) throws Exception{
        // 第一步,建立一個webbook,對應一個Excel檔案
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步,在webbook中新增一個sheet,對應Excel檔案中的sheet
        HSSFSheet sheet = wb.createSheet(sheetName);
        // 第三步,在sheet中新增表頭第0行,注意老版本poi對Excel的行數列數有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步,建立單元格,並設定值表頭 設定表頭居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 建立一個居中格式
        //HSSFCell cell = row.createCell(0);
        String[] datakey=new String[head.length];
        for(int i=0,m=1;i<head.length;i++,m++){
            HSSFCell  cell = row.createCell(i);
            cell.setCellValue(head[i]);
            cell.setCellStyle(style);
            datakey[i]=m+"";
        }
        // 第五步,寫入實體資料 實際應用中這些資料從資料庫得到,
        for (int i = 0; i < list.size(); i++){
            HSSFRow datarow = sheet.createRow((int)i+1);
            // row = sheet.createRow((int) i + 1);
            // 第四步,建立單元格,並設定值
            for(int j=0;j<head.length;j++){
                //System.out.println(list.get(i).get("1"));
                //System.out.print(list.get(i).get(datakey[j]).toString());
                datarow.createCell(j).setCellValue(list.get(i).get(datakey[j]).toString());
            }
        }
        // 第六步,將檔案存到指定位置
            FileOutputStream fout = new FileOutputStream(path);
            wb.write(fout);
            fout.close();
    }
}

Mapper.xml

 <!-- web:匯出保險訂單 "1"、"2"表示excel對應的第一行單元格的每一列-->
  <select id="exportOrderSecureList" parameterType="java.util.Map" resultType="java.util.Map">
    select
    a.company as "1",
    a.insurance_type as "2",

    a.car_brand as "3",
    DATE_FORMAT(a.insure_time,'%Y-%m-%d') as "4",
    a.name as "5",
    a.phone as "6",
    DATE_FORMAT(a.order_time,'%Y-%m-%d %T') as "7"
    from
    tb_order_secure a

    where
    1=1
    <if test="company !=null and company !=''">
    <![CDATA[
    and a.company=#{company}
    ]]>
    </if>

    <if test="insuranceType !=null and insuranceType !=''">
    <![CDATA[
    and a.insurance_type=#{insuranceType}
    ]]>
    </if>

    <if test="carBrand !=null and carBrand !=''">
    <![CDATA[
    and INSTR(a.car_brand,#{carBrand})>0
    ]]>
    </if>

    <if test="name !=null and name !=''">
    <![CDATA[
    and INSTR(a.name,#{name})>0
    ]]>
    </if>

    <if test="phone !=null and phone !=''">
    <![CDATA[
    and INSTR(a.phone,#{phone})>0
    ]]>
    </if>

    order by a.order_time desc
  </select>
<!-- web:匯出保險訂單 "1"、"2"表示excel對應的第一行單元格的每一列--> <select id="exportOrderSecureList" parameterType="java.util.Map" resultType="java.util.Map"> select a.company as "1", a.insurance_type as "2", a.car_brand as "3", DATE_FORMAT(a.insure_time,'%Y-%m-%d') as "4", a.name as "5", a.phone as "6", DATE_FORMAT(a.order_time,'%Y-%m-%d %T') as "7" from tb_order_secure a where 1=1 <if test="company !=null and company !=''"> <![CDATA[ and a.company=#{company} ]]> </if> <if test="insuranceType !=null and insuranceType !=''"> <![CDATA[ and a.insurance_type=#{insuranceType} ]]> </if> <if test="carBrand !=null and carBrand !=''"> <![CDATA[ and INSTR(a.car_brand,#{carBrand})>0 ]]> </if> <if test="name !=null and name !=''"> <![CDATA[ and INSTR(a.name,#{name})>0 ]]> </if> <if test="phone !=null and phone !=''"> <![CDATA[ and INSTR(a.phone,#{phone})>0 ]]> </if> order by a.order_time desc </select>

controller.java

@Autowired
     private UploadFileOss uploadFileOss; //簡單檔案上傳的工具類
     /**
     * <p class="detail">
     * 功能:匯出保險訂單excel
     * </p>
     * @author zhaoyang
     * @date 2017年6月17日
     * @param request
     * @param company
     * @param insuranceType
     * @param carBrand
     * @param name
     * @param phone
     * @return
     */
    @RequestMapping(value = "/exportOrderSecureList.web", produces = { "application/json;charset=utf-8" },method=RequestMethod.POST)
    @ResponseBody
    public ResponseObj exportOrderSecureList(HttpServletRequest request,String minTime,String maxTime,String company,String insuranceType,String carBrand,String name,String phone){
        ResponseObj obj = new ResponseObj(ViewShowEnums.INFO_SUCCESS.getStatus(), ViewShowEnums.INFO_SUCCESS.getDetail());
        if(company.indexOf("請選擇保險公司")>=0){
            obj.setShowMessage("請選擇保險公司");
            obj.setStatus(ViewShowEnums.ERROR_FAILED.getStatus());
            return obj;
        }
        Map<String, Object> m =new HashMap<>();
        m.put("company", company);
        if(insuranceType.indexOf("請選擇險種")>=0){

        }else{
            m.put("insuranceType", insuranceType);
        }
        m.put("carBrand", carBrand);
        m.put("name", name);
        m.put("phone", phone);
        m.put("minTime", minTime);
        m.put("maxTime", maxTime);
        List<Map<String, Object>> list = orderSecureService.exportOrderSecureList(m);
        if(list!=null && !list.isEmpty()){

        }else{
            obj.setShowMessage("匯出資料為空,請選擇保險公司");
            obj.setStatus(ViewShowEnums.ERROR_FAILED.getStatus());
            return obj;
        }
        Date date=new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String nowTime=dateFormat.format(date);
        String sheetName="保險訂單";
        String[] head={"保險公司","險種","車型","投保時間","姓名","聯絡電話","下單時間"};
        //String path="C:\\保險訂單匯出"+nowTime+".xls";
        //path位置在伺服器裡
        String path = request.getSession().getServletContext().getRealPath("/static/保險訂單匯出"+nowTime+".xls");
        ExportExcel ee=new ExportExcel(); //匯出excel的工具類
        String url="";
        if(list!=null && !list.isEmpty()){
            try {
                ee.outExcel(sheetName, head, list, path);
                url=uploadFileOss.samplesUpload(path, "保險訂單匯出"+nowTime+".xls"); //簡單檔案上傳的工具類,上傳成功後返回阿里雲的URL
                System.out.println(url);
            } catch (Exception e) {
                obj.setShowMessage("匯出失敗");
                obj.setStatus(ViewShowEnums.ERROR_FAILED.getStatus());
                return obj;
            }
        }
        obj.setData(url);
        return obj;
    }