XLSTransformer生成excel文件
jxls的使用方法:
1)声明一个XLSTransformer对象,生成方式就是使用new操作符
XLSTransformer transformer = new XLSTransformer();
2)得到Template的FIle:
String xlsTemplateFileName = this.getClass().getClassLoader().getResource("template.xls");
3)利用XLSTransformer的类的方法生成Excel文件
String xlsFileName = "D:"+File.separator+"resule.xls";
Map map= new HashMap();
map .put("news1","news1 ");
map .put("news2","news2");
transformer.transformXLS(xlsTemplateFileName , map, xlsFileName);
XLSTransformer类的transformXLS方法的定义如下:
public void transformXLS(String srcFilePath, Map map , String destFilePath) throws ParsePropertyException,
IOException其中:srcFilePath:是Template文件的全文件名(包含路径)
map :需要传入Excel里面的一个Map,jxls根据Template里面的定义和Map里面的对象对Template进行解析,
将Map里面的对象值填入到Excel文件中
destFilePath:需要生成的Excel文件的全文件名(包含路径)
Struts.xml配置
<action name="reportTest" method="reportTest" class="org.bkgd.tpmis.report.web.action.T"> <result type="stream"> <param name="contentType">application/octet-stream</param> <param name="inputName">inputStream</param> <param name="contentDisposition">attachment;filename="reportTest.xls"</param> <param name="bufferSize">4096</param> </result> </action>
java代码
public class T { private InputStream inputStream; public String reportTest() { try { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> m1 = new HashMap<String,Object>(); m1.put("PRONAME", "项目1"); m1.put("PLANTYPE", "计划1"); m1.put("PROTYPE", "类别1"); Map<String, Object> m2 = new HashMap<String,Object>(); m2.put("PRONAME", "项目2"); m2.put("PLANTYPE", "计划2"); m2.put("PROTYPE", "类别2"); list.add(m1); list.add(m2); //------------------------开始报表 Map<String, Object> para = new HashMap<String, Object>(); para.put("result", list); XLSTransformer transformer = new XLSTransformer(); Workbook wb; try { //模板路径 String classPath = this.getClass().getClassLoader().getResource("report/resource/reportTest.xls").getPath(); //真实导出路径 String classPath2 = this.getClass().getClassLoader().getResource("report/temp/reportTest.xls").getPath(); transformer.transformXLS(classPath, para,classPath2); //在classPath2下生成excel文件 inputStream = new FileInputStream(new File(classPath2)); wb = transformer.transformXLS(new FileInputStream(classPath),para); //获得Workbook对象 wb.write(new FileOutputStream(classPath2)); //导出Excel } catch (Exception e) { throw new ReportException(e); } } catch (Exception e) { e.printStackTrace(); } return "success"; } public InputStream getInputStream() { return inputStream; } public void setInputStream(InputStream inputStream) { this.inputStream = inputStream; } }
reportTest.xls文件格式