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文件截圖:


發佈了25 篇原創文章 · 獲贊 12 · 訪問量 33萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章