jxls使用模板生成excel文件

一. 简述

Jxls是基于Jakarta POI AIP的Excel报表生成工具, 可以生成自定义模板的Excel报表, 它采用类似于JSP标签的方式定义Excel模板, 非常简单.

为什么不用POI? 因为POI通常要求我们在Java代码中进行样式和字体的设计.


二. 标签

1. <jx:forEach items="${ ? }" var=" ? "> </jx:forEach>  : 用于迭代, 属性有2个, 一个是items, 一个是var, 类似jstl

2. <jx:if test="${ ? }" > </jx:if> :  用于逻辑判断, 有一个属性test, 类似jstl

3. $[sum(position)] :  求和

4. $[min(position)] :  求最大值

5. $[max(position)] :  求最小值

6. $[average(position)] :  求平均值

7. $[count(position)] :  求数量


三. 实例

1. 工程图及所需Jar

jxls使用模板生成excel文件_第1张图片


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模板文件和生成文件

jxls使用模板生成excel文件_第2张图片


jxls使用模板生成excel文件_第3张图片


4. 下载源码请猛击这里: http://download.csdn.net/detail/zdp072/7490803


你可能感兴趣的:(jxls使用模板生成excel文件)