XLSTransformer生成excel文件简单示例

项目结构图:

项目中所用到的jar,可以到http://www.findjar.com/index.x下载


ExcelUtil类源码:

package util;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.jxls.exception.ParsePropertyException;
import net.sf.jxls.transformer.XLSTransformer;
/**
 * Excel生成类.
 */
public class ExcelUtil {
	/**
	 * 根据模板生成Excel文件.
	 * @param templateFileName 模板文件.
	 * @param list 模板中存放的数据.
	 * @param resultFileName 生成的文件.
	 */
	public void createExcel(String templateFileName, List<?> list, String resultFileName){
		//创建XLSTransformer对象
		XLSTransformer transformer = new XLSTransformer();
		//获取java项目编译后根路径
		URL url = this.getClass().getClassLoader().getResource("");
		//得到模板文件路径
		String srcFilePath = url.getPath() + templateFileName;
		Map<String,Object> beanParams = new HashMap<String,Object>();
		beanParams.put("list", list);
		String destFilePath = url.getPath() + resultFileName;
		try {
			//生成Excel文件
			transformer.transformXLS(srcFilePath, beanParams, destFilePath);
		} catch (ParsePropertyException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

Test类源码:

package test;

import java.util.ArrayList;
import java.util.List;

import po.Fruit;
import util.ExcelUtil;
/**
 * 测试类.
 */
public class Test {

	public static void main(String[] args) {
		List<Fruit> list = new ArrayList<Fruit>();
		list.add(new Fruit("苹果",2.01f));
		list.add(new Fruit("桔子",2.05f));
		String templateFileName = "template/template.xls";
		String resultFileName = "result/fruit.xls";
		new ExcelUtil().createExcel(templateFileName,list,resultFileName);

	}

}

template.xls模板文件截图:

注意:如果你是用的office 2007生成的excel模板,要另存为97-2003版本的。


Fruit类源码:

package po;
/**
 * 水果.
 */
public class Fruit {
	/**
	 * 水果名称.
	 */
	private String name;
	/**
	 * 水果价格.
	 */
	private float price;
	
	
	public Fruit() {
		super();
	}
	
	public Fruit(String name, float price) {
		super();
		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;
	}
	
}

生成fruit.xls文件截图:


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值