java-jxls根據模板導出excel


1、pom引入

<dependency>
    <groupId>org.jxls</groupId>
    <artifactId>jxls</artifactId>
    <version>2.4.7</version>
</dependency>
<dependency>
    <groupId>org.jxls</groupId>
    <artifactId>jxls-poi</artifactId>
    <version>1.0.16</version>
</dependency>
<dependency>
    <groupId>org.jxls</groupId>
    <artifactId>jxls-jexcel</artifactId>
    <version>1.0.7</version>
</dependency>

2、創建excel管理工具類

public class JxlsUtils {
    /**
     * 根據模板生成excel,新文件放入download文件夾下
     * @param templateFileName 模板文件名
     * @param newFileName 新文件名
     * @param model 填充數據
     * @return 新文件名
     * @throws IOException
     */
    public static String exportExcel(String templateFileName,String newFileName, Map<String, Object> model) throws IOException{
        // 獲取模板文件
        InputStream is = new FileInputStream(new File("E://"+templateFileName));
        // 輸出
        OutputStream os = new FileOutputStream(RuoYiConfig.getDownloadPath() +newFileName);
        Context context = PoiTransformer.createInitialContext();
        if (model != null) {
            for (String key : model.keySet()) {
                context.putVar(key, model.get(key));
            }
        }
        JxlsHelper jxlsHelper = JxlsHelper.getInstance();
        Transformer transformer  = jxlsHelper.createTransformer(is, os);
        //獲得配置
        JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator)transformer.getTransformationConfig().getExpressionEvaluator();
        //設置靜默模式,不報警告
        evaluator.getJexlEngine().setSilent(true);
        //函數強制,自定義功能
        Map<String, Object> funcs = new HashMap<String, Object>();
        funcs.put("utils", new JxlsUtils());    //添加自定義功能
        evaluator.getJexlEngine().setFunctions(funcs);
        //必須要這個,否則表格函數統計會錯亂
        jxlsHelper.setUseFastFormulaProcessor(false).processTemplate(context, transformer);
        return newFileName;
    }

}

  3、controller中調用方法

public void exportExcel(){
        // 綁定數據
        Map<String, Object> model = new HashMap<String, Object>();
        String fileName="test.xls";
        model.put("yearT", 2021);//年份
        model.put("monthT", 1);//月份
        JxlsUtils.exportExcel(fileName, fileName, model);//根據模板生成excel
}

  4、創建excel模板

(注意:如果你是用的office 2007生成的excel模板,要另存為97-2003版本的。看網上說的。)

jxls官網:http://jxls.sourceforge.net/getting_started.html

創建時注意增加批注:例子

 

 

 

 

 

 (lastCell的范圍要大於等於填充數據的最右下角單元格,增加批注的位置是變量開始的單元格。)

5、遇到的問題

a.m³單位輸入可以使用輸入法漢語模式下,輸入“立方米”,然后選中m³。

b.10的幾次方輸入模板后導出的excel會報錯,目前未解決。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM