XLSTransformer生成excel文件简单示例
发布时间:2025-12-09 14:01:38
浏览次数:4
项目结构图:
项目中所用到的jar,可以到http://www.findjar.com/index.x下载
ExcelUtil类源码:
[java] view plain
copy
- packageutil;
- importjava.io.IOException;
- importjava.net.URL;
- importjava.util.HashMap;
- importjava.util.List;
- importjava.util.Map;
- importnet.sf.jxls.exception.ParsePropertyException;
- importnet.sf.jxls.transformer.XLSTransformer;
- /**
- *Excel生成类.
- */
- publicclassExcelUtil{
- /**
- *根据模板生成Excel文件.
- *@paramtemplateFileName模板文件.
- *@paramlist模板中存放的数据.
- *@paramresultFileName生成的文件.
- */
- publicvoidcreateExcel(StringtemplateFileName,List<?>list,StringresultFileName){
- //创建XLSTransformer对象
- XLSTransformertransformer=newXLSTransformer();
- //获取java项目编译后根路径
- URLurl=this.getClass().getClassLoader().getResource(“”);
- //得到模板文件路径
- StringsrcFilePath=url.getPath()+templateFileName;
- Map<String,Object>beanParams=newHashMap<String,Object>();
- beanParams.put(“list”,list);
- StringdestFilePath=url.getPath()+resultFileName;
- try{
- //生成Excel文件
- transformer.transformXLS(srcFilePath,beanParams,destFilePath);
- }catch(ParsePropertyExceptione){
- e.printStackTrace();
- }catch(IOExceptione){
- e.printStackTrace();
- }
- }
- }
Test类源码:
[java] view plain
copy
- packagetest;
- importjava.util.ArrayList;
- importjava.util.List;
- importpo.Fruit;
- importutil.ExcelUtil;
- /**
- *测试类.
- */
- publicclassTest{
- publicstaticvoidmain(String[]args){
- List<Fruit>list=newArrayList<Fruit>();
- list.add(newFruit(“苹果”,2.01f));
- list.add(newFruit(“桔子”,2.05f));
- StringtemplateFileName=“template/template.xls”;
- StringresultFileName=“result/fruit.xls”;
- newExcelUtil().createExcel(templateFileName,list,resultFileName);
- }
- }
template.xls模板文件截图:
注意:如果你是用的office 2007生成的excel模板,要另存为97-2003版本的。
Fruit类源码:
[java] view plain
copy
- packagepo;
- /**
- *水果.
- */
- publicclassFruit{
- /**
- *水果名称.
- */
- privateStringname;
- /**
- *水果价格.
- */
- privatefloatprice;
- publicFruit(){
- super();
- }
- publicFruit(Stringname,floatprice){
- super();
- this.name=name;
- this.price=price;
- }
- publicStringgetName(){
- returnname;
- }
- publicvoidsetName(Stringname){
- this.name=name;
- }
- publicfloatgetPrice(){
- returnprice;
- }
- publicvoidsetPrice(floatprice){
- this.price=price;
- }
- }
生成fruit.xls文件截图: