在JSF的开发中,我们也常常会用到导出Excel的功能,以下代码是我在开发中的测试小实例:
首先是展示页面testExcel.xhtml:
<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:rich="http://richfaces.org/rich"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:t="http://myfaces.apache.org/tomahawk"
xmlns:c="http://java.sun.com/jstl/core">
<!--引用统一的模板-->
<ui:composition template="pages/templates/Demotemplate.xhtml">
<!--header区域-->
<ui:define name="pageHeader">导出Excel界面</ui:define>
<!--body区域-->
<ui:define name="body">
<h:form>
<h:commandButton action="#{loginC.getExcel}" value="导出Excel"/>
</h:form>
</ui:define>
</ui:composition>
</html>
在manageBean为loginC里面的实现方法为:
public void getExcel(){
System.out.println("in the method of getExcel()!! ");
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
ExcelBaseBean te = new ExcelBaseBean();
te.setColnumHeader("ID");
te.setColnumHeader("姓名");
te.setColnumHeader("性别");
te.setColnumHeader("出生日期");
List list = userdao.getAllUser();
HSSFWorkbook wb;
response.reset();//清空输出流
response.setContentType("application/ms-excel");//定义输出类型
try {
wb = te.makeExcel(list);
response.setHeader("Content-Disposition", "attachment;filename="
+ new String("导出excel".getBytes("gb2312"), "ISO8859-1")
+ ".xls");
wb.write(response.getOutputStream());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FacesContext.getCurrentInstance().responseComplete(); //这语句很重要 如果不写,则会出现导出的Excel中内容为提交页面的代码,而不能显示出真正的查询的数据;
}
这里我用的是apache的poi实现生成Excel的功能(数据路用的是ibatis),以下是实现生成Excel的一个工具类:
public class ExcelBaseBean {
private List headerList = new ArrayList();
/*
* 该方法用于显示excel表格的第一行的数据(每一列数据的标题)
* */
public void setColnumHeader(String titleHeader){
headerList.add(titleHeader);
}
/*
* 该方法用于构造生成excel表格;
* */
public HSSFWorkbook makeExcel(List list) throws Exception{
System.out.println("in the method of makeExcel!!");
HSSFWorkbook book=new HSSFWorkbook();
HSSFSheet sheet=book.createSheet("sheet1");
HSSFRow row;
HSSFCell cell;
int start = 0;
if(headerList != null && headerList.size() > 0 ){
start = 1;
row=sheet.createRow(0);
for(int i = 0;i < headerList.size();i++){
cell = row.createCell(i);
String v = (String) headerList.get(i);
cell.setCellValue(v);
}
}
for(int i = start;i < list.size();i++){
row = sheet.createRow(i);
LinkedHashMap mapValue = (LinkedHashMap) list.get(i);
Iterator it = (Iterator) mapValue.entrySet().iterator();
int cellSum = 0;
while(it.hasNext()){
Map.Entry e = (Map.Entry) it.next();
cell = row.createCell(cellSum);
cell.setCellValue(e.getValue().toString());
cellSum++;
}
}
return book;
}
}