使用Jxls 实现Java 导出Excel

一、引入所需jar包

		
            org.jxls
            jxls
            2.4.3
        

        
            org.jxls
            jxls-poi
            1.0.14
        

        
            org.jxls
            jxls-jexcel
            1.0.0
        

        
            jexcelapi
            jxl
            2.6
        

        
            net.sf.jxls
            jxls-reader
            1.0.6
        

二、配置编译时过滤excel文件
此配置为保证编译后,准备的excel模板能正常打开。

		
                org.apache.maven.plugins
                maven-resources-plugin
                
                    UTF-8
                    
                    
                        xls
                        xlsx
                        doc
                        docx
                    
                
           

三、Excel 导出工具类

import org.joda.time.DateTime;
import org.jxls.common.Context;
import org.jxls.expression.JexlExpressionEvaluator;
import org.jxls.transform.Transformer;
import org.jxls.transform.poi.PoiTransformer;
import org.jxls.util.JxlsHelper;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zjm
 * @descripton Jxls工具类
 * @time 2020/8/25 16:42
 * @modify
 */
public class JxlsUtils {


    public static final String DATE_FORMAT_DEFAULT = "yyyy-MM-dd HH:mm:ss";

    //导出excel
    public static void exportExcel(InputStream is, OutputStream os, Map model) throws IOException {
        Context context = PoiTransformer.createInitialContext();
        if (model != null) {
//            for (String key : model.keySet()) {
//                context.putVar(key, model.get(key));
//            }
            for (Map.Entry Entry : model.entrySet()) {
                context.putVar(Entry.getKey(), Entry.getValue());
            }
        }
        JxlsHelper jxlsHelper = JxlsHelper.getInstance();
        Transformer transformer = jxlsHelper.createTransformer(is, os);
        //获得配置
        JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator();
        //设置静默模式,不报警告
        evaluator.getJexlEngine().setSilent(true);
        //函数强制,自定义功能
        Map funcs = new HashMap<>();
        funcs.put("utils", new JxlsUtils());
        evaluator.getJexlEngine().setFunctions(funcs);
        //必须要这个,否则表格函数统计会错乱
        jxlsHelper.setUseFastFormulaProcessor(false).processTemplate(context, transformer);
    }

    //导出excel
    public static void exportExcel(String templatePath, OutputStream os, Map model) throws Exception {
        File template = getTemplate(templatePath);
        if (template != null) {
            exportExcel(new FileInputStream(template), os, model);
        } else {
            throw new Exception("Excel 模板未找到。");
        }
    }

    //获取jxls模板
    public static File getTemplate(String path) {
        File template = new File(path);
        if (template.exists()) {
            return template;
        }
        return null;
    }

    //日期格式化处理
    public String dateFmt(Date date, String fmt) {
        if (date == null) {
            return "";
        }
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat(fmt);
            return dateFormat.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";

    }

    public String timeSecondFmt(Object timeSecondObj, String fmt) {
        if (timeSecondObj == null) {
            return null;
        }
        Long second = Long.valueOf(String.valueOf(timeSecondObj));
        Date date = new Date();
        date.setTime(second * Constant.NUM_1000);
        DateTime dateTime = new DateTime(date);
        return dateTime.toString(fmt);
    }

    public String timeSecondFmt(Object timeSecondObj) {
        return timeSecondFmt(timeSecondObj, DATE_FORMAT_DEFAULT);
    }


    //if判断
    public Object ifelse(boolean b, Object o1, Object o2) {
        return b ? o1 : o2;
    }

    //设置响应头、文件名
    public static void setResponse(HttpServletResponse response,String fileName) throws UnsupportedEncodingException {
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("content-disposition", "attachment;filename=" + fileName );
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");

    }
}

四、准备excel模板
在这里插入图片描述
表格中插入批注
使用Jxls 实现Java 导出Excel_第1张图片
使用Jxls 实现Java 导出Excel_第2张图片

五、调用controller

 /***
     * Description: 导出数据
     * Author: zjm
     * Return: void
    */
    @PostMapping("/exportInfo")
    public String exportPersonInfo(@RequestBody TestParam param,HttpServletResponse response){
        try {
            Map result = new HashMap<>();
            List testBean= iTestService.exportInfo(param);
            result.put("disData",testBean);
            // 配置输出文件名
            String fileName =  "导出数据"+".xlsx";
            JxlsUtils.setResponse(response,fileName);
            // 设置excel模版路径
            InputStream tplIs = TestController.class.getClassLoader().getResourceAsStream("模板路径/模板.xlsx");
            JxlsUtils.exportExcel(tplIs, response.getOutputStream(), result);
            return "导出成功!";
        } catch (Exception e) {
            logger.error("导出数据失败!");
            return "导出失败!";
        }
    }

你可能感兴趣的:(笔记,java,excel,开发语言)