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文件格式

