jxls使用模板生成excel文件

xiaoxiao2021-02-28  139

jxls使用模板生成excel文件

一. 简述

Jxls是一个小而易用的Java库, 它用于根据excel模板文件生成对应的excel数据文件.

使用Jxls只需要几行代码就可以建立非常复杂的excel报表, 我们需要做的工作室建立excel模板文件, 完成所需要的格式、公式、宏等,

然后写几行代码调用Jxls引擎解析excel模板文件并将数据作为参数输入到报表文件中.

二. 实例

1. 工程图及所需Jar

2. 代码展示

① 实体Bean

/** * 水果类 */ public class Fruit { private String name; // 水果名称 private float price; // 水果价格 public Fruit() { } public Fruit(String name, float price) { this.name = name; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } } ② 核心工具类 /** * Excel生成类. */ public class ExcelUtil { /** * 根据模板生成Excel文件. * @param templateFileName 模板文件. * @param list 模板中存放的数据. * @param resultFileName 生成的文件. */ public void createExcel(String templateFileName, List<?> list, String resultFileName){ try { //创建XLSTransformer对象 XLSTransformer transformer = new XLSTransformer(); //获取java项目编译后根路径 URL url = this.getClass().getClassLoader().getResource(""); //得到模板文件路径 String srcFilePath = url.getPath() + templateFileName; Map<String,Object> map = new HashMap<String,Object>(); map.put("list", list); String destFilePath = url.getPath() + resultFileName; //生成Excel文件 transformer.transformXLS(srcFilePath, map, destFilePath); } catch (Exception e) { throw new RuntimeException("error happens...", e); } } } ③ 测试类 /** * 测试类. */ public class Client { public static void main(String[] args) { List<Fruit> list = new ArrayList<Fruit>(); list.add(new Fruit("苹果",20.0f)); list.add(new Fruit("桔子",30.0f)); String templateFileName = "template.xlsx"; String resultFileName = "result.xlsx"; new ExcelUtil().createExcel(templateFileName,list,resultFileName); } } 3. excel模板文件和生成文件

转载请注明原文地址: https://www.6miu.com/read-34313.html

最新回复(0)