XLSTransformer生成excel一个简单的演示示例文件
2024-10-15 07:45:05
项目结构图:
在这些项目中使用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文件截图:
最新文章
- 用Java语言编写一个简易画板
- redis部署
- 2016 大连网赛---Different GCD Subarray Query(GCD离散+树状数组)
- mysql 导入text 到数据库
- JavaWeb学习之JSTL自定义标签库的使用、JSTL自定义函数库(7)
- spring中配置jndi数据源
- ios PullToRefresh using animated GIF or image array or Vector image
- SpringMVC进行文件的上传以及多文件的上传(转)
- sql两表联合查询
- POJ1410 Intersection 计算几何
- Redis一次数据丢失(转)
- CentOS7更换国内源
- Functional Language
- 使用Sphinx编写文档
- [Leetcode 392]判断子序列 Is Subsequence
- Linux 创建用户 限制SFTP用户只能访问某个目录
- ubuntu下zaibbix3.2报警搭建
- week4
- Haskell语言学习笔记(30)MonadCont, Cont, ContT
- PAT 1075 PAT Judge[比较]
热门文章
- 《生活在Linux中》之:prefer function to alias in Bash
- Spring.Net 初探
- $.ajax()详解
- SAE+Java+jetty
- 《高性能 JavaScript》读书笔记(一)
- js 正则学习小记之NFA引擎
- Android APK反编译就这么简单 详细解释(简介)
- Python学习笔记21:数据库操作(sqlite3)
- 【Unity 3D】学习笔记三十八:角色控制器
- ASP.NET Web API和ASP.NET Web MVC中使用Ninject