使用POI和DynaBean导出Excel的完整例子



之前做过几个POI的Excel处理,但都没有去整理过。俗话说好记性敌不过烂笔头,所以今天做了一个觉得把代码整理一遍贴出来。

LazyDynaBean!

使用到的东西: struts1.2

jdbc

Apache commons-beanutils.jar

Apache commons-lang.jar

POI 3.0

闲话不多说,上代码....

struts的配置文件:

 

Xml代码 复制代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">  
  3.   
  4. <struts-config>  
  5.   <data-sources />  
  6.   <form-beans >  
  7.   
  8.   
  9.   </form-beans>  
  10.   <global-exceptions />  
  11.   <global-forwards >  
  12.     <forward name="logs" path="/logs/logs.jsp"></forward>  
  13.   </global-forwards>  
  14.   <action-mappings >  
  15.     <!-- 日志管理 -->  
  16.     <action path="/logsAction" type="logs.LogsAction"></action>  
  17.   </action-mappings>  
  18.   <message-resources parameter="ApplicationResources" />  
  19. </struts-config>  

 
Action:

Java代码 复制代码  收藏代码
  1. package logs;  
  2.   
  3. import java.io.OutputStream;  
  4. import java.util.List;  
  5.   
  6. import javax.servlet.http.HttpServletRequest;  
  7. import javax.servlet.http.HttpServletResponse;  
  8.   
  9. import org.apache.commons.beanutils.DynaBean;  
  10. import org.apache.commons.beanutils.LazyDynaBean;  
  11. import org.apache.commons.lang.StringUtils;  
  12. import org.apache.struts.action.Action;  
  13. import org.apache.struts.action.ActionForm;  
  14. import org.apache.struts.action.ActionForward;  
  15. import org.apache.struts.action.ActionMapping;  
  16.   
  17. import logs.dao.LogsDao;  
  18.   
  19. /** 
  20.  * 日志 
  21.  * 
  22.  * @author zhongzy 
  23.  * @时间 2011-4-13 
  24.  */  
  25. public class LogsAction extends Action {  
  26.     public ActionForward execute(ActionMapping mapping, ActionForm form,  
  27.             HttpServletRequest request, HttpServletResponse response)  
  28.             throws Exception {  
  29.         request.setCharacterEncoding("GBK");  
  30.         String method = StringUtils.defaultIfEmpty(request.getParameter("method"), "");  
  31.         if ("exportExcel".equals(method)) {  
  32.             return exportExcel(mapping, form, request, response);  
  33.         }  
  34.         // 权限控制  
  35.         String menuId = request.getParameter("menuId");  
  36.         int pageSize = 10;  
  37.         int pageNum = 1;  
  38.         int rowCount = 0;  
  39.   
  40.         String pageStr = request.getParameter("pageNum");  
  41.   
  42.         if (pageStr != null) {  
  43.             pageNum = Integer.parseInt(pageStr);  
  44.         } else {  
  45.             pageNum = 1;  
  46.         }  
  47.         try {  
  48.             List<DynaBean> data = LogsDao.selectLogs(request);  
  49.             rowCount = LogsDao.getLogsCount(request);  
  50.             int pageCount = rowCount % pageSize == 0 ? rowCount / pageSize  
  51.                     : (rowCount / pageSize + 1);  
  52.             request.setAttribute("pageNum", pageNum);  
  53.             request.setAttribute("count", rowCount);  
  54.             request.setAttribute("countPage", pageCount);  
  55.             request.setAttribute("list", data);  
  56.         } catch (Exception e) {  
  57.             e.printStackTrace();  
  58.         }  
  59.   
  60.         return new ActionForward("logs");  
  61.     }  
  62.   
  63.     public ActionForward exportExcel(ActionMapping mapping, ActionForm form,  
  64.             HttpServletRequest request, HttpServletResponse response)  
  65.             throws Exception {  
  66.         response.setContentType("application/x-download");  
  67.         response.setCharacterEncoding("GBK");  
  68.         response.addHeader("Content-Disposition""attachment;filename=Logs.xls");  
  69.         List<DynaBean> list = LogsDao.selectLogs(request);  
  70.         OutputStream out = response.getOutputStream();  
  71.         LogsExcel excel = new LogsExcel();  
  72.         excel.generalTableExport("前台登录日志", title(), list, out);  
  73.         out.close();  
  74.         return null;  
  75.     }  
  76.   
  77.     public DynaBean title() {  
  78.         DynaBean title = new LazyDynaBean();  
  79.         //|角色|用户编号(用户ID)|用户名|昵称(用户名称)|日志时间|主机IP|主机名  
  80.         title.set("log_id""序号");  
  81.         title.set("rolename""角色");  
  82.         title.set("userid""用户编号(用户ID)");  
  83.         title.set("username""用户名");  
  84.         title.set("nickname""昵称(用户名称)");  
  85.         title.set("logdate""登录时间");  
  86.         title.set("hostip""主机IP");  
  87.         title.set("hostname""主机名");  
  88.         return title;  
  89.     }  
  90. }  
package logs;

import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import logs.dao.LogsDao;

/**
 * 日志
 *
 * @author zhongzy
 * @时间 2011-4-13
 */
public class LogsAction extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		request.setCharacterEncoding("GBK");
		String method = StringUtils.defaultIfEmpty(request.getParameter("method"), "");
		if ("exportExcel".equals(method)) {
			return exportExcel(mapping, form, request, response);
		}
		// 权限控制
		String menuId = request.getParameter("menuId");
		int pageSize = 10;
		int pageNum = 1;
		int rowCount = 0;

		String pageStr = request.getParameter("pageNum");

		if (pageStr != null) {
			pageNum = Integer.parseInt(pageStr);
		} else {
			pageNum = 1;
		}
		try {
			List<DynaBean> data = LogsDao.selectLogs(request);
			rowCount = LogsDao.getLogsCount(request);
			int pageCount = rowCount % pageSize == 0 ? rowCount / pageSize
					: (rowCount / pageSize + 1);
			request.setAttribute("pageNum", pageNum);
			request.setAttribute("count", rowCount);
			request.setAttribute("countPage", pageCount);
			request.setAttribute("list", data);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return new ActionForward("logs");
	}

	public ActionForward exportExcel(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		response.setContentType("application/x-download");
		response.setCharacterEncoding("GBK");
		response.addHeader("Content-Disposition", "attachment;filename=Logs.xls");
		List<DynaBean> list = LogsDao.selectLogs(request);
		OutputStream out = response.getOutputStream();
		LogsExcel excel = new LogsExcel();
		excel.generalTableExport("前台登录日志", title(), list, out);
		out.close();
		return null;
	}

	public DynaBean title() {
		DynaBean title = new LazyDynaBean();
		//|角色|用户编号(用户ID)|用户名|昵称(用户名称)|日志时间|主机IP|主机名
		title.set("log_id", "序号");
		title.set("rolename", "角色");
		title.set("userid", "用户编号(用户ID)");
		title.set("username", "用户名");
		title.set("nickname", "昵称(用户名称)");
		title.set("logdate", "登录时间");
		title.set("hostip", "主机IP");
		title.set("hostname", "主机名");
		return title;
	}
}

 
由于是小应用就直接在Action调用Dao了,Dao:

Java代码 复制代码  收藏代码
  1. package logs.dao;  
  2.   
  3. import java.sql.ResultSet;  
  4. import java.sql.ResultSetMetaData;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. import javax.servlet.http.HttpServletRequest;  
  9.   
  10. import org.apache.commons.beanutils.DynaBean;  
  11. import org.apache.commons.beanutils.LazyDynaBean;  
  12. import org.apache.commons.lang.StringUtils;  
package logs.dao;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.commons.lang.StringUtils;
Java代码 复制代码  收藏代码
  1. import org.apache.commons.logging.Log;  
  2. import org.apache.commons.logging.LogFactory;  
  3.   
  4. /** 
  5.  * @author zhongzy 
  6.  * @version 1.0 
  7.  */  
  8. public class LogsDao {  
  9. <span style="white-space: pre;">    </span>private static log = LogFactory.getLog(LogsDao .class);  
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author zhongzy
 * @version 1.0
 */
public class LogsDao {
<span style="white-space: pre;">	</span>private static log = LogFactory.getLog(LogsDao .class);
Java代码 复制代码  收藏代码
  1. /** 
  2.  * 查询前台登录日志 
  3.  * @return 
  4.  * @author zhongzy 2011-04-13 
  5.  */  
  6. public static List<DynaBean> selectLogs(HttpServletRequest request) {  
  7.     String sql = "  SELECT log_id, rolename, userid, username, nickname, logdate, hostip, hostname \n";  
  8.     sql += "    FROM tc_logs    \n";  
  9.     sql += "    WHERE   1=1     \n";  
  10.     sql += getCondition(request);  
  11.   
  12.     List result = null;  
  13.     ResultSet rs = null;  
  14.     try {  
  15.         System.out.println(sql);  
  16.         rs = .....//查询出结果集  
  17.         //取数据库的列名  
  18.         ResultSetMetaData o_resultSetMetaData = rs.getMetaData();  
  19.         int n_total = o_resultSetMetaData.getColumnCount();  
  20.         result = new ArrayList<DynaBean>();  
  21.         DynaBean bean = null;  
  22.         while (rs.next()) {  
  23.             bean = new LazyDynaBean();  
  24.             for(int i = 1; i <= n_total; i++) {  
  25.                 String s_columnName = o_resultSetMetaData.getColumnLabel(i);  
  26.                 String s_value = rs.getString(s_columnName);  
  27.                 bean.set(s_columnName, s_value);  
  28.             }  
  29.             result.add(bean);  
  30.         }  
  31.     }  
  32.     catch(Exception ex) {  
  33.         log.info("查询前台登录日志失败!" + ex.getMessage());  
  34.         ex.printStackTrace();  
  35.     }  
  36.     finally {  
  37.         if (rs != null) {  
  38.             rs.close();  
  39.         }  
  40.     }  
  41.     return result;  
  42. }  
  43.   
  44. /** 
  45.  * 查询日志总数 
  46.  * @param request 
  47.  * @return 
  48.  * @author zhongzy 2011-04-13 
  49.  */  
  50. public static int getLogsCount(HttpServletRequest request) {  
  51.     String sql = "  SELECT COUNT(1) AS dataTotal \n";  
  52.     sql += "    FROM tc_logs    \n";  
  53.     sql += "    WHERE 1=1       \n";  
  54.     sql += getCondition(request);  
  55.     int result = 0;  
  56.     try {  
  57.         result  = ...//查询  
	/**
	 * 查询前台登录日志
	 * @return
	 * @author zhongzy 2011-04-13
	 */
	public static List<DynaBean> selectLogs(HttpServletRequest request) {
		String sql = "	SELECT log_id, rolename, userid, username, nickname, logdate, hostip, hostname \n";
		sql += "	FROM tc_logs	\n";
		sql += "	WHERE	1=1		\n";
		sql += getCondition(request);

		List result = null;
		ResultSet rs = null;
		try {
			System.out.println(sql);
			rs = .....//查询出结果集
			//取数据库的列名
			ResultSetMetaData o_resultSetMetaData = rs.getMetaData();
		    int n_total = o_resultSetMetaData.getColumnCount();
			result = new ArrayList<DynaBean>();
			DynaBean bean = null;
			while (rs.next()) {
				bean = new LazyDynaBean();
				for(int i = 1; i <= n_total; i++) {
					String s_columnName = o_resultSetMetaData.getColumnLabel(i);
					String s_value = rs.getString(s_columnName);
					bean.set(s_columnName, s_value);
				}
				result.add(bean);
			}
		}
		catch(Exception ex) {
			log.info("查询前台登录日志失败!" + ex.getMessage());
			ex.printStackTrace();
		}
		finally {
			if (rs != null) {
				rs.close();
			}
		}
		return result;
	}

	/**
	 * 查询日志总数
	 * @param request
	 * @return
	 * @author zhongzy 2011-04-13
	 */
	public static int getLogsCount(HttpServletRequest request) {
		String sql = "	SELECT COUNT(1) AS dataTotal \n";
		sql += "	FROM tc_logs	\n";
		sql += "	WHERE 1=1		\n";
		sql += getCondition(request);
		int result = 0;
		try {
			result  = ...//查询
Java代码 复制代码  收藏代码
  1.         }  
  2.         catch(Exception ex) {  
  3.             log.info("查询前台登录日志总数失败!" + ex.getMessage());  
  4.         }  
  5.         return result;  
  6.     }  
  7.     /** 
  8.      * 查询语句条件 
  9.      * @param request 
  10.      * @return 
  11.      * @author zhongzy 2011-04-13 
  12.      */  
  13.     protected static String getCondition(HttpServletRequest request) {  
  14.         String sql = "";  
  15.         String startDate = StringUtils.defaultIfEmpty(request.getParameter("startDate"), "");  
  16.         String endDate = StringUtils.defaultIfEmpty(request.getParameter("endDate"), "");  
  17.         String rolename = StringUtils.defaultIfEmpty(request.getParameter("rolename"), "");  
  18.         String username = StringUtils.defaultIfEmpty(request.getParameter("username"), "");  
  19.         String nickname = StringUtils.defaultIfEmpty(request.getParameter("nickname"), "");  
  20.         String hostip = StringUtils.defaultIfEmpty(request.getParameter("hostip"), "");  
  21.         sql += StringUtils.isEmpty(startDate)== true ? "" : "   AND logdate>='" + startDate +"'\n";  
  22.         sql += StringUtils.isEmpty(endDate)== true ? "" : " AND logdate<='" + endDate + "'\n";  
  23.         sql += StringUtils.isEmpty(rolename)==true ? "" : " AND rolename='" + rolename + "'\n" ;  
  24.         sql += StringUtils.isEmpty(username)==true ? "" : " AND username LIKE '%" + username.trim() + "%'\n" ;  
  25.         sql += StringUtils.isEmpty(nickname)==true ? "" : " AND nickname LIKE '%" + nickname.trim() + "%'\n" ;  
  26.         sql += StringUtils.isEmpty(hostip)==true ? "" : "   AND hostip LIKE '%" + hostip.trim() + "%'\n" ;  
  27.   
  28.         return sql;  
  29.     }  
  30. }  
		}
		catch(Exception ex) {
			log.info("查询前台登录日志总数失败!" + ex.getMessage());
		}
		return result;
	}
	/**
	 * 查询语句条件
	 * @param request
	 * @return
	 * @author zhongzy 2011-04-13
	 */
	protected static String getCondition(HttpServletRequest request) {
		String sql = "";
		String startDate = StringUtils.defaultIfEmpty(request.getParameter("startDate"), "");
		String endDate = StringUtils.defaultIfEmpty(request.getParameter("endDate"), "");
		String rolename = StringUtils.defaultIfEmpty(request.getParameter("rolename"), "");
		String username = StringUtils.defaultIfEmpty(request.getParameter("username"), "");
		String nickname = StringUtils.defaultIfEmpty(request.getParameter("nickname"), "");
		String hostip = StringUtils.defaultIfEmpty(request.getParameter("hostip"), "");
		sql += StringUtils.isEmpty(startDate)== true ? "" : "	AND	logdate>='" + startDate +"'\n";
		sql += StringUtils.isEmpty(endDate)== true ? "" : "	AND	logdate<='" + endDate + "'\n";
		sql += StringUtils.isEmpty(rolename)==true ? "" : "	AND rolename='" + rolename + "'\n" ;
		sql += StringUtils.isEmpty(username)==true ? "" : "	AND username LIKE '%" + username.trim() + "%'\n" ;
		sql += StringUtils.isEmpty(nickname)==true ? "" : "	AND nickname LIKE '%" + nickname.trim() + "%'\n" ;
		sql += StringUtils.isEmpty(hostip)==true ? "" : "	AND hostip LIKE '%" + hostip.trim() + "%'\n" ;

		return sql;
	}
}

 

最后是Excel导出处理类:

Java代码 复制代码  收藏代码
  1. package logs;import java.io.IOException;  
  2. import java.io.OutputStream;  
  3. import java.util.Iterator;  
  4. import java.util.List;  
  5.   
  6. import org.apache.commons.beanutils.DynaBean;  
  7. import org.apache.commons.beanutils.DynaClass;  
  8. import org.apache.commons.beanutils.DynaProperty;  
  9. import org.apache.commons.beanutils.LazyDynaBean;  
  10. import org.apache.poi.hssf.usermodel.HSSFCell;  
  11. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
  12. import org.apache.poi.hssf.usermodel.HSSFFont;  
  13. import org.apache.poi.hssf.usermodel.HSSFRow;  
  14. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  15. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  16. import org.apache.poi.hssf.util.HSSFColor;  
  17.   
  18. /** 
  19.  * 简单 Excel 导出类 
  20.  * @author zhongzy at 2011-04-13 
  21.  * 
  22.  */  
  23.   
  24. public class LogsExcel {  
  25.     /** 
  26.      * 通用表格导出Excel, 单sheet 
  27.      * @param sheetName     sheet显示文字 
  28.      * @param tableTitle    表格标题 
  29.      * @param tableData     数据 
  30.      * @param out           输出流 
  31.      * @throws IOException 
  32.      */  
  33.     public void generalTableExport(String sheetName, DynaBean title, List data, OutputStream out) throws IOException {  
  34.         HSSFWorkbook workbook = new HSSFWorkbook();  
  35.         HSSFSheet sheet = workbook.createSheet(sheetName);  
  36.   
  37.         /** 
  38.          * 数据区域个列样式 
  39.          */  
  40.         HSSFCellStyle cellStyle = workbook.createCellStyle(); // 字体用的风格  
  41.         cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 左右居中  
  42.         cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 上下居中  
  43.         cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框  
  44.         cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); // 左边框  
  45.         cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); // 右边框  
  46.         cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); // 上边框  
  47.         cellStyle.setWrapText(true); // 字符换行  
  48.   
  49.         HSSFFont cellFont5 = workbook.createFont();  
  50.         cellFont5.setFontHeightInPoints((short10); // 字号  
  51.         cellFont5.setFontName("宋体"); // 设置为宋体  
  52.         cellStyle.setFont(cellFont5);  
  53.   
  54.         /** 
  55.          * 表头样式 
  56.          */  
  57.         HSSFCellStyle titleStyle = workbook.createCellStyle();  
  58.         //字体  
  59.         HSSFFont titlefont = workbook.createFont();  
  60.         titlefont.setFontHeightInPoints((short12); // 字体高度  
  61.         titlefont.setColor(HSSFColor.DARK_GREEN.index); // 字体颜色  
  62.         titlefont.setFontName("宋体"); // 字体  
  63.         titlefont.setBoldweight(HSSFFont.COLOR_NORMAL); // 字体加粗  
  64.         titleStyle.setFont(titlefont);  
  65.         /** 
  66.          * 边框 
  67.          */  
  68.         titleStyle.setBorderBottom(HSSFCellStyle.BORDER_DOUBLE);  
  69.         titleStyle.setBorderLeft((short)1);  
  70.         titleStyle.setBorderRight((short)1);  
  71.         titleStyle.setBorderTop(HSSFCellStyle.BORDER_DOUBLE);  
  72.         titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);              //样式  
  73.         titleStyle.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index);        //前景色  
  74.         titleStyle.setWrapText(false); // 标题栏字符不予换行  
  75.   
  76.   
  77.         /** 
  78.          * 处理标题栏 
  79.          */  
  80.         int row = 1// 行号  
  81.         DynaClass titleDc = title.getDynaClass();               //DynaClass  
  82.         DynaProperty[] titledp =  titleDc.getDynaProperties();  //属性  
  83.         HSSFRow rowTitle = sheet.createRow(0); // 创建一行  
  84.         rowTitle.setHeight((short500); // 高  
  85.   
  86.         for (int i=0; i<titledp.length; i++) {  
  87.             String key = (String) titledp[i].getName();         // 字段  
  88.             String value = (String) title.get(key);             //值  
  89.             HSSFCell celli = rowTitle.createCell((short) i); // 创建一列  
  90.             celli.setEncoding(HSSFCell.ENCODING_UTF_16); // 设置单元格字符  
  91.             celli.setCellValue(value);  
  92.             celli.setCellStyle(titleStyle);  
  93.             sheet.setColumnWidth((short)i, (short)(value.length() * 899));      //设置标题各列的宽度  
  94.         }  
  95.   
  96.         /** 
  97.          * 处理数据列表 
  98.          */  
  99.         for (Iterator iter = data.iterator(); iter.hasNext();) { // 根据list的大小生成  
  100.             // execel  
  101.             DynaBean bean = (LazyDynaBean) iter.next();  
  102.             HSSFRow rowi = sheet.createRow(row); // 创建一行  
  103.             rowi.setHeight((short300); // 高  
  104.             int cell = 0// 列号  
  105.             DynaClass dc = bean.getDynaClass();  
  106.             DynaProperty[] dp =  dc.getDynaProperties();  
  107.   
  108.             for (int i=0; i<dp.length; i++) {  
  109.                 String key = (String) dp[i].getName(); // 字段值  
  110.                 String value = (String) bean.get(key);  
  111.                 HSSFCell celli = rowi.createCell((short) cell); // 创建一列  
  112.                 celli.setEncoding(HSSFCell.ENCODING_UTF_16); // 设置单元格字符  
  113.                 celli.setCellValue(value);  
  114.                 cell++;  
  115.             }  
  116.             row++;  
  117.         }  
  118.         workbook.write(out);  
  119.         out.flush();  
  120.     }  
  121. }  
package logs;import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaClass;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

/**
 * 简单 Excel 导出类
 * @author zhongzy at 2011-04-13
 *
 */

public class LogsExcel {
	/**
	 * 通用表格导出Excel, 单sheet
	 * @param sheetName		sheet显示文字
	 * @param tableTitle	表格标题
	 * @param tableData		数据
	 * @param out			输出流
	 * @throws IOException
	 */
	public void generalTableExport(String sheetName, DynaBean title, List data, OutputStream out) throws IOException {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet(sheetName);

		/**
		 * 数据区域个列样式
		 */
		HSSFCellStyle cellStyle = workbook.createCellStyle(); // 字体用的风格
		cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 左右居中
		cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 上下居中
		cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
		cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); // 左边框
		cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); // 右边框
		cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); // 上边框
		cellStyle.setWrapText(true); // 字符换行

		HSSFFont cellFont5 = workbook.createFont();
		cellFont5.setFontHeightInPoints((short) 10); // 字号
		cellFont5.setFontName("宋体"); // 设置为宋体
		cellStyle.setFont(cellFont5);

		/**
		 * 表头样式
		 */
		HSSFCellStyle titleStyle = workbook.createCellStyle();
		//字体
		HSSFFont titlefont = workbook.createFont();
		titlefont.setFontHeightInPoints((short) 12); // 字体高度
		titlefont.setColor(HSSFColor.DARK_GREEN.index); // 字体颜色
		titlefont.setFontName("宋体"); // 字体
		titlefont.setBoldweight(HSSFFont.COLOR_NORMAL); // 字体加粗
		titleStyle.setFont(titlefont);
		/**
		 * 边框
		 */
		titleStyle.setBorderBottom(HSSFCellStyle.BORDER_DOUBLE);
		titleStyle.setBorderLeft((short)1);
		titleStyle.setBorderRight((short)1);
		titleStyle.setBorderTop(HSSFCellStyle.BORDER_DOUBLE);
		titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);				//样式
		titleStyle.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index);		//前景色
		titleStyle.setWrapText(false); // 标题栏字符不予换行


		/**
		 * 处理标题栏
		 */
		int row = 1; // 行号
		DynaClass titleDc = title.getDynaClass();				//DynaClass
		DynaProperty[] titledp =  titleDc.getDynaProperties();	//属性
		HSSFRow rowTitle = sheet.createRow(0); // 创建一行
		rowTitle.setHeight((short) 500); // 高

		for (int i=0; i<titledp.length; i++) {
			String key = (String) titledp[i].getName(); 		// 字段
			String value = (String) title.get(key);				//值
			HSSFCell celli = rowTitle.createCell((short) i); // 创建一列
			celli.setEncoding(HSSFCell.ENCODING_UTF_16); // 设置单元格字符
			celli.setCellValue(value);
			celli.setCellStyle(titleStyle);
			sheet.setColumnWidth((short)i, (short)(value.length() * 899));		//设置标题各列的宽度
		}

		/**
		 * 处理数据列表
		 */
		for (Iterator iter = data.iterator(); iter.hasNext();) { // 根据list的大小生成
			// execel
			DynaBean bean = (LazyDynaBean) iter.next();
			HSSFRow rowi = sheet.createRow(row); // 创建一行
			rowi.setHeight((short) 300); // 高
			int cell = 0; // 列号
			DynaClass dc = bean.getDynaClass();
			DynaProperty[] dp =  dc.getDynaProperties();

			for (int i=0; i<dp.length; i++) {
				String key = (String) dp[i].getName(); // 字段值
				String value = (String) bean.get(key);
				HSSFCell celli = rowi.createCell((short) cell); // 创建一列
				celli.setEncoding(HSSFCell.ENCODING_UTF_16); // 设置单元格字符
				celli.setCellValue(value);
				cell++;
			}
			row++;
		}
		workbook.write(out);
		out.flush();
	}
}

 JSP调用:

Java代码 复制代码  收藏代码
  1. <c:set var="ctx" value="${pageContext.request.contextPath}"></c:set><script type="text/javascript">    
  2. function exportExcel() {  
  3.             document.location.href = "${ctx}/logsAction.do?method=exportExcel";  
  4.         }  
  5.  </script>  
  6.   
  7. <input name="export" type="button" class="button" οnclick="exportExcel();" value="结果导出Excel"/>  
  8.   
  9. jsp部分就自己去完善吧。^^  
<c:set var="ctx" value="${pageContext.request.contextPath}"></c:set><script type="text/javascript">  
function exportExcel() {
	    	document.location.href = "${ctx}/logsAction.do?method=exportExcel";
	    }
 </script>

<input name="export" type="button" class="button" οnclick="exportExcel();" value="结果导出Excel"/>

jsp部分就自己去完善吧。^^
  http://yose.iteye.com/blog/1001790
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值