- 论坛徽章:
- 0
|
关键词:
POI
Excel
ValueList
Struts
注意:本文针对对
Struts
,Value List有一定使用经验的开发人员,如果你不是在web环境下使用
POI
,建议你直接去看
POI
的教程。
1.问题由来
在此之前,我一直用valuelist来完成查询并显示结果,效果不错。valuelist可以导出excel,csv,但是一用之下,并没有相象的那么好,它导出的excel并不是真正的excel文件,是一个html的文本文件,这样由于某些处理上的不完善,在我这里出现了导出的文件在打开时,表头和下面的内容错开,并且有多余的空列。如果对它的有关源代码进行修改,做到正常显示是没问题的,但是如果客户的需求再变一点点,比如要设置一定的格式,用它来做就不太方便了。所以我只好寻求另一种方案,最后终于找到
POI
,看它的介绍很不错,按照它的指南一试之下,也很简单,于是决定就用它了。现在的问题就是怎样取得valuelist的查询结果,并且用
POI
导出到Excel中。
2.从web页面动作时调用的Action
在我们真正用到的查询action里只要设置好三个属性值就可以了.
package com.sogoodsoft.test.export.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.*;
import com.sogoodsoft.framework.exporter.ExportBaseAction;
/**
* 导出查询的excel表
*
* @author Albert Song
* @version 1.0
*/
public class ExportQueryAction extends ExportBaseAction {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//列名,必须和applicationContext.xml中对应的sql的列名一致。
// 顺序不必一致
String colNames[]={"stu_no","stu_name"};
//Excel表的表头,列名对应的中文,必须和列名的顺序对应
String titleNames[]={"学号","姓名"};
//applicataionContext.xml中sql对应的id
String valueListName="testList";
// 这三项必须设置
setColNames(colNames);
setTitleNames(titleNames);
set
ValueList
Name(valueListName);
return super.export(mapping,form,request,response);
}
}
3.在ExportBaseAction 中取得valuelist的查询结果
valuelist可以不用
Struts
单独使用,我这里是在
Struts
中的用法,代码大概像这样
package com.sogoodsoft.framework.exporter;
import java.util.List;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.*;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import net.mlw.vlh.*;
import net.mlw.vlh.web.
ValueList
RequestUtil;
import com.sogoodsoft.util.BaseAction;
/**
*
*
* @author Albert Song
* @version 1.0
*/
public class ExportBaseAction extends BaseAction {
/*
*可导出的最大记录数
*/
private final static int MAX_NUM_PER_PAGE=10000;
private
ValueList
Handler get
ValueList
Handler() {
WebApplicationContext context = WebApplicationContextUtils
.getWebApplicationContext(getServlet().getServletContext());
return (
ValueList
Handler) context.getBean("valueListHandler",
ValueList
Handler.class);
}
public ActionForward export(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ValueList
Info vli=
ValueList
RequestUtil.build
ValueList
Info(request);
vli.setPagingNumberPer(MAX_NUM_PER_PAGE);
ValueList
valueList = get
ValueList
Handler().get
ValueList
(valueListName,
vli);
List ls=new ArrayList();
ls.add(titleNames);
int colWidths[]=new int[colNames.length];//列宽
for(int i=0;i
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/29515/showart_238365.html |
|