原理是從頁面點擊鏈接觸發action,并在action方法中從session中取得list。這樣做的缺點是,如果頁面顯示數據時對數據使用了判斷、迭代數據顯示,那麼在action中同樣要去做同樣的工作。而我最理想的方法是將頁面生成的html代碼中的table里的數據直接導入到xls中,這樣就不需再做複雜的業務處理。
JSP頁面添加觸發action鏈接:
<a href="javascript:;" onClick="javascript:toXML();">通過poi導出XLS</a>
javascript函數:
function toXML(){
form1.action = "toXLS.action";
form1.submit();
}
action類:
package biz.ceeport.struts.action;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* @author winston
* @version CreationTime: 2010-2-25
* @class declaration:
*/
public class DownloadAction extends ActionSupport{
public void toXLS() throws Exception {
List list = (List)ServletActionContext.getRequest().getSession().getAttribute("mylist");
//create HSSFWorkbook
HSSFWorkbook workbook = new HSSFWorkbook();
//create HSSFSheet named user
HSSFSheet sheet = workbook.createSheet("user");
//create row
HSSFRow rowTitle = sheet.createRow(0);
//create cell
HSSFCell cellTitle = rowTitle.createCell((short)(0));
//filled cell
cellTitle.setCellValue(getText("common_activityName"));
cellTitle = rowTitle.createCell((short)1);
cellTitle.setCellValue(getText("common_activityTime2"));
cellTitle = rowTitle.createCell((short)2);
cellTitle.setCellValue(getText("common_signupEndTime"));
cellTitle = rowTitle.createCell((short)3);
cellTitle.setCellValue(getText("common_signupNum"));
for (int i = 0; i < 5; i++) {
HashMap map = (HashMap)list.get(i);
HSSFRow row = sheet.createRow(i+1);
HSSFCell cell = row.createCell((short)0);
cell.setCellValue(map.get("ACTIVITY_NAME").toString());
cell = row.createCell((short)1);
cell.setCellValue(map.get("END_TIME").toString());
cell = row.createCell((short)2);
cell.setCellValue(map.get("SHOW_END_TIME").toString());
cell = row.createCell((short)3);
cell.setCellValue(((HashMap)map.get("SIGNUPPEPOERNUM")).get("NUM").toString());
}
//set response content type
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("application/vnd.ms-excel");
//set the name of download file
response.addHeader("Content-Disposition","attachment;filename=350000.xls");
//get response stream
OutputStream out=response.getOutputStream();
//add workbook to OutpustStream
workbook.write(out);
out.close();
}
}
struts.xml中:
<!-- 導出xls文檔-->
<action name="toXLS" class="biz.ceeport.struts.action.DownloadAction" method="toXLS">
<result name="success" type="chain">manageActilist</result>
<result name="error">/error.jsp</result>
</action>
測試運行后的結果是正確的,但中文亂碼
在CSDN上找到同類文章,解決了亂碼問題:
http://blog.csdn.net/flyever581549/archive/2008/11/11/3275850.aspx
cell.setEncoding(HSSFWorkbook.ENCODING_UTF_16);