1 用spring MVC 生成Excel和PDF
http://blog.csdn.net/linlzk/archive/2008/11/27/3389925.aspx
2 Spring MVC export data to Excel file via AbstractExcelView
http://www.mkyong.com/spring-mvc/spring-mvc-export-data-to-excel-file-via-abstractexcelview/
3 用Java的iText实现PDF报表
http://muder2007.blog.163.com/blog/static/45933070200793152351991/
使用JXL请关注:JXL2.6:解决JXL的IndexOutOfBoundsException getSheet问题,使用了修复版本的jxl包http://liuzidong.iteye.com/blog/1071677
一 工程代码结构图片

二 具体代码如下
1 index.jsp

Java代码 复制代码 收藏代码
  1. <%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  3. <%@ taglib uri="/WEB-INF/c.tld" prefix="c"%>
  4. <html>
  5. <head>
  6. <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery/jquery-1.4.4.min.js"></script>
  7. <%@ include file="/common/meta.jsp"%>
  8. </head>
  9. <script type="text/javascript">
  10. $(document).ready(function(){
  11. $("#exec").click(function(){
  12. //获取下拉框的值
  13. var titlesValue = "";//$("#columns").find("option:selected").text();
  14. $("#columns").find("option:selected").each(function(){ //由于复选框一般选中的是多个,所以可以循环输出
  15. titlesValue += ($(this).text())+",";
  16. });
  17. var names =  $("#columns").val();
  18. $("#colums").val(names);
  19. $("#titles").val(titlesValue);
  20. });
  21. });
  22. </script>
  23. <body>&nbsp;&nbsp; &nbsp;
  24. <div style="border: 1px solid #ccc; width: 50%;height:200px;align:center;margin-top:200px;margin-left:300px;padding:50px;">
  25. <form action="${pageContext.request.contextPath}/view/excel.do" method="post">
  26. <input type="submit" value="使用POI导出Excel"><br>
  27. </form>
  28. <hr><br>
  29. <form method="post" action="${pageContext.request.contextPath}/view/jxlExcel.do">
  30. <select id="columns" multiple="multiple" style="width:100px;height:120px;">
  31. <option value="id">ID</option>
  32. <option value="name">姓名</option>
  33. <option value="sex">性别</option>
  34. <option value="age">年龄</option>
  35. <option value="password">密码</option>
  36. <option value="address">地址</option>
  37. </select>
  38. <input type="hidden" id="titles" name="titles">
  39. <input type="hidden" id="colums" name="colums">
  40. <input type="submit" id="exec" value="使用JXL导出Excel"><br>
  41. </form>
  42. <hr><br>
  43. <form action="${pageContext.request.contextPath}/view/pdf.do" method="post">
  44. <input type="submit" value="导出PDF"><br>
  45. <br>
  46. <img src="${pageContext.request.contextPath}/img/car.do" width="100px" height="50px"/>
  47. </form>
  48. </div>
  49. </body>
  50. </html>
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ taglib uri="/WEB-INF/c.tld" prefix="c"%>
<html><head><script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery/jquery-1.4.4.min.js"></script><%@ include file="/common/meta.jsp"%></head>  <script type="text/javascript">$(document).ready(function(){$("#exec").click(function(){//获取下拉框的值var titlesValue = "";//$("#columns").find("option:selected").text();               $("#columns").find("option:selected").each(function(){ //由于复选框一般选中的是多个,所以可以循环输出titlesValue += ($(this).text())+",";          });   var names =   $("#columns").val();               $("#colums").val(names);$("#titles").val(titlesValue);             });});    </script><body>&nbsp;&nbsp; &nbsp;  <div style="border: 1px solid #ccc; width: 50%;height:200px;align:center;margin-top:200px;margin-left:300px;padding:50px;">   <form action="${pageContext.request.contextPath}/view/excel.do" method="post">    <input type="submit" value="使用POI导出Excel"><br>  </form>     <hr><br><form method="post" action="${pageContext.request.contextPath}/view/jxlExcel.do">   <select id="columns" multiple="multiple" style="width:100px;height:120px;"><option value="id">ID</option><option value="name">姓名</option><option value="sex">性别</option><option value="age">年龄</option><option value="password">密码</option><option value="address">地址</option></select> <input type="hidden" id="titles" name="titles"><input type="hidden" id="colums" name="colums"><input type="submit" id="exec" value="使用JXL导出Excel"><br>                         </form>   <hr><br><form action="${pageContext.request.contextPath}/view/pdf.do" method="post">       <input type="submit" value="导出PDF"><br>                 <br><img src="${pageContext.request.contextPath}/img/car.do" width="100px" height="50px"/></form>    </div>     </body>
</html>

2 ViewController.java

Java代码 复制代码 收藏代码
  1. package com.liuzd.sj.web;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import org.springframework.stereotype.Controller;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RequestParam;
  11. import org.springframework.web.servlet.ModelAndView;
  12. import com.liuzd.sj.entity.Student;
  13. import com.liuzd.sj.entity.User;
  14. /**
  15. * 生成excel或PDF类型试图 根据参数进行数据组装,并跳转到相应的视图页面 View Controller Bean<br>
  16. */
  17. @Controller
  18. @RequestMapping("/view")
  19. public class ViewController {
  20. @RequestMapping("/excel")
  21. public ModelAndView viewExcel(HttpServletRequest request,
  22. HttpServletResponse response) {
  23. Map model = new HashMap();
  24. model.put("list", getStudents());
  25. return new ModelAndView(new ViewExcel(), model);
  26. }
  27. private List getStudents(){
  28. List stuList = new ArrayList();
  29. // 构造数据
  30. Student stu1 = new Student("gaoxiang1""male1""20060101"1);
  31. Student stu2 = new Student("gaoxiang2""male2""20060102"2);
  32. Student stu3 = new Student("gaoxiang3""male3""20060103"3);
  33. Student stu4 = new Student("gaoxiang4""male4""20060104"4);
  34. Student stu5 = new Student("gaoxiang5""male5""20060105"5);
  35. stuList.add(stu1);
  36. stuList.add(stu2);
  37. stuList.add(stu3);
  38. stuList.add(stu4);
  39. stuList.add(stu5);
  40. return stuList;
  41. }
  42. @RequestMapping("/jxlExcel")
  43. public ModelAndView viewJxlExcel(@RequestParam("titles") String titles,@RequestParam("colums") String colums,HttpServletRequest request,
  44. HttpServletResponse response) {
  45. String [] array1 = null;
  46. if(null != colums && colums.indexOf(",") != -1){
  47. array1 = colums.split(",");
  48. }
  49. String [] array2 = null;
  50. if(null != titles && titles.indexOf(",") != -1){
  51. array2 = titles.split(",");
  52. }
  53. Map model = new HashMap();
  54. // 构造数据
  55. List<User> users = new ArrayList<User>();
  56. users.add(new User("123456""李逵""123""成都市""1"23));
  57. users.add(new User("123457""李四""124""北京市""2"53));
  58. users.add(new User("123458""李三""125""河南市""0"73));
  59. users.add(new User("123459""李五""126""大路市""3"93));
  60. model.put("list", users);
  61. model.put("columns", array1);
  62. model.put("titles", array2);
  63. return new ModelAndView(new JXLExcelView(), model);
  64. }
  65. @RequestMapping("/pdf")
  66. public ModelAndView viewPDF(HttpServletRequest request,
  67. HttpServletResponse response) throws Exception {
  68. Map model = new HashMap();
  69. model.put("list", getStudents());
  70. return new ModelAndView(new ViewPDF(), model);
  71. }
  72. }
package com.liuzd.sj.web;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;import com.liuzd.sj.entity.Student;
import com.liuzd.sj.entity.User;/*** 生成excel或PDF类型试图 根据参数进行数据组装,并跳转到相应的视图页面 View Controller Bean<br>*/@Controller
@RequestMapping("/view")
public class ViewController {@RequestMapping("/excel")public ModelAndView viewExcel(HttpServletRequest request,HttpServletResponse response) {Map model = new HashMap();        model.put("list", getStudents());       return new ModelAndView(new ViewExcel(), model);}private List getStudents(){List stuList = new ArrayList();// 构造数据Student stu1 = new Student("gaoxiang1", "male1", "20060101", 1);Student stu2 = new Student("gaoxiang2", "male2", "20060102", 2);Student stu3 = new Student("gaoxiang3", "male3", "20060103", 3);Student stu4 = new Student("gaoxiang4", "male4", "20060104", 4);Student stu5 = new Student("gaoxiang5", "male5", "20060105", 5);  stuList.add(stu1);stuList.add(stu2);stuList.add(stu3);stuList.add(stu4);stuList.add(stu5);return stuList;}@RequestMapping("/jxlExcel")public ModelAndView viewJxlExcel(@RequestParam("titles") String titles,@RequestParam("colums") String colums,HttpServletRequest request,HttpServletResponse response) {       String [] array1 = null;if(null != colums && colums.indexOf(",") != -1){array1 = colums.split(",");}String [] array2 = null;if(null != titles && titles.indexOf(",") != -1){array2 = titles.split(",");}            Map model = new HashMap();// 构造数据List<User> users = new ArrayList<User>();users.add(new User("123456", "李逵", "123", "成都市", "1", 23));users.add(new User("123457", "李四", "124", "北京市", "2", 53));users.add(new User("123458", "李三", "125", "河南市", "0", 73));users.add(new User("123459", "李五", "126", "大路市", "3", 93));model.put("list", users);     model.put("columns", array1);model.put("titles", array2);       return new ModelAndView(new JXLExcelView(), model);}@RequestMapping("/pdf")public ModelAndView viewPDF(HttpServletRequest request,HttpServletResponse response) throws Exception {Map model = new HashMap();        model.put("list", getStudents());           return new ModelAndView(new ViewPDF(), model);}
}

3 JXLExcelView.java

Java代码 复制代码 收藏代码
  1. package com.liuzd.sj.web;
  2. import java.io.IOException;
  3. import java.io.OutputStream;
  4. import java.net.URLEncoder;
  5. import java.util.List;
  6. import java.util.Map;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. import jxl.Workbook;
  10. import jxl.WorkbookSettings;
  11. import jxl.format.Alignment;
  12. import jxl.format.VerticalAlignment;
  13. import jxl.write.WritableCellFormat;
  14. import jxl.write.WritableFont;
  15. import jxl.write.WritableSheet;
  16. import jxl.write.WritableWorkbook;
  17. import jxl.write.WriteException;
  18. import jxl.write.biff.RowsExceededException;
  19. import org.apache.commons.beanutils.PropertyUtils;
  20. import org.springframework.web.servlet.view.document.AbstractJExcelView;
  21. import com.liuzd.sj.entity.User;
  22. public class JXLExcelView extends AbstractJExcelView {
  23. private String[] columnNames = new String[] { "编号""姓名""年龄""性别""密码",
  24. "地址" };
  25. private String[] dbColumnNames = new String[] { "id""name""age""sex",
  26. "password""address" };
  27. private Integer[] columnWidths = new Integer[] { 202020202020 };
  28. @Override
  29. public void buildExcelDocument(Map<String, Object> map,
  30. WritableWorkbook work, HttpServletRequest req,
  31. HttpServletResponse response) {
  32. String [] titles = (String[])map.get("titles");
  33. if(null != titles && titles.length > 0){
  34. columnNames = titles;
  35. }
  36. String [] columns = (String[])map.get("columns");
  37. if(null != columns &&  columns.length > 0){
  38. dbColumnNames = columns;
  39. }
  40. OutputStream os = null;
  41. try {
  42. String excelName = "用户信息.xls";
  43. // 设置response方式,使执行此controller时候自动出现下载页面,而非直接使用excel打开
  44. response.setContentType("APPLICATION/OCTET-STREAM");
  45. response.setHeader("Content-Disposition""attachment; filename="
  46. + URLEncoder.encode(excelName, "UTF-8"));
  47. os = response.getOutputStream();
  48. // sheet名称
  49. String sheetName = "用户信息";
  50. // 全局设置
  51. WorkbookSettings setting = new WorkbookSettings();
  52. java.util.Locale locale = new java.util.Locale("zh""CN");
  53. setting.setLocale(locale);
  54. setting.setEncoding("ISO-8859-1");
  55. // 创建工作薄
  56. work = Workbook.createWorkbook(os); // 建立excel文件
  57. // 创建第一个工作表
  58. jxl.write.WritableSheet ws = work.createSheet(sheetName, 1); // sheet名称
  59. // 添加标题
  60. addColumNameToWsheet(ws);
  61. List<User> list = (List<User>) map.get("list");
  62. writeContext(ws, list);
  63. catch (Exception e) {
  64. e.printStackTrace();
  65. finally {
  66. // 写入文件
  67. try {
  68. work.write();
  69. work.close();
  70. os.flush();
  71. os.close();
  72. catch (WriteException e) {
  73. e.printStackTrace();
  74. catch (IOException e) {
  75. e.printStackTrace();
  76. }
  77. }
  78. }
  79. private <T> void writeContext(WritableSheet wsheet, List<T> list) {
  80. int rows = list.size();
  81. jxl.write.Label wlabel = null;
  82. jxl.write.WritableCellFormat wcf = getFormat();
  83. int cols = dbColumnNames.length;
  84. String columnName = null;
  85. Object value = null;
  86. try {
  87. for (int i = 0; i < rows; i++) {
  88. T t = (T) list.get(i);
  89. for (int j = 0; j < cols; j++) {
  90. columnName = dbColumnNames[j].toLowerCase();
  91. value = PropertyUtils.getProperty(t, columnName);
  92. wlabel = new jxl.write.Label(j, (i + 1), value + "", wcf);
  93. wlabel = new jxl.write.Label(j, (i + 1), value + "");
  94. wsheet.addCell(wlabel);
  95. }
  96. }
  97. catch (Exception e) {
  98. e.printStackTrace();
  99. }
  100. }
  101. // 添加标题样式
  102. private void addColumNameToWsheet(jxl.write.WritableSheet wsheet)
  103. throws RowsExceededException, WriteException {
  104. // 设置excel标题
  105. jxl.write.WritableFont wfont = getFont();
  106. if (null == wfont) {
  107. wfont = new WritableFont(WritableFont.ARIAL,
  108. WritableFont.DEFAULT_POINT_SIZE, WritableFont.BOLD);
  109. }
  110. jxl.write.WritableCellFormat wcfFC = getFormat();
  111. if (null == wcfFC) {
  112. wcfFC = new jxl.write.WritableCellFormat(wfont);
  113. try {
  114. wcfFC.setWrap(true);// 自动换行
  115. wcfFC.setAlignment(Alignment.CENTRE);
  116. wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);// 设置对齐方式
  117. catch (WriteException e) {
  118. e.printStackTrace();
  119. }
  120. }
  121. jxl.write.Label wlabel1 = null;
  122. String[] columNames = columnNames;
  123. if (null == columNames)
  124. return;
  125. int colSize = columNames.length;
  126. Integer[] colsWidth = columnWidths;
  127. if (null == colsWidth) {
  128. colsWidth = new Integer[colSize];
  129. for (int i = 0; i < colSize; i++) {
  130. colsWidth[i] = 20;
  131. }
  132. }
  133. int temp = 0;
  134. String colName = null;
  135. for (int i = 0; i < colSize; i++) {
  136. colName = columNames[i];
  137. if (null == colName || "".equals(colName))
  138. colName = "";
  139. wlabel1 = new jxl.write.Label(i, 0, colName, wcfFC);
  140. wsheet.addCell(wlabel1);
  141. temp = colsWidth[i].intValue();
  142. // 默认设置列宽
  143. temp = temp == 0 ? 20 : temp;
  144. wsheet.setColumnView(i, temp);
  145. }
  146. }
  147. // 设置格式
  148. private WritableCellFormat getFormat() {
  149. jxl.write.WritableFont wfont = getFont();
  150. jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(
  151. wfont);
  152. try {
  153. wcfFC.setWrap(true);
  154. wcfFC.setAlignment(Alignment.CENTRE);
  155. wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);
  156. catch (WriteException e) {
  157. e.printStackTrace();
  158. }
  159. return wcfFC;
  160. }
  161. // 设置字体
  162. private WritableFont getFont() {
  163. return new WritableFont(WritableFont.ARIAL,
  164. WritableFont.DEFAULT_POINT_SIZE, WritableFont.BOLD);
  165. }
  166. }
package com.liuzd.sj.web;import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.Alignment;
import jxl.format.VerticalAlignment;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.web.servlet.view.document.AbstractJExcelView;import com.liuzd.sj.entity.User;public class JXLExcelView extends AbstractJExcelView {private String[] columnNames = new String[] { "编号", "姓名", "年龄", "性别", "密码","地址" };private String[] dbColumnNames = new String[] { "id", "name", "age", "sex","password", "address" };private Integer[] columnWidths = new Integer[] { 20, 20, 20, 20, 20, 20 };@Overridepublic void buildExcelDocument(Map<String, Object> map,WritableWorkbook work, HttpServletRequest req,HttpServletResponse response) {String [] titles = (String[])map.get("titles");if(null != titles && titles.length > 0){columnNames = titles;}String [] columns = (String[])map.get("columns");if(null != columns &&  columns.length > 0){dbColumnNames = columns;}OutputStream os = null;try {String excelName = "用户信息.xls";// 设置response方式,使执行此controller时候自动出现下载页面,而非直接使用excel打开response.setContentType("APPLICATION/OCTET-STREAM");response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(excelName, "UTF-8"));os = response.getOutputStream();// sheet名称String sheetName = "用户信息";// 全局设置WorkbookSettings setting = new WorkbookSettings();java.util.Locale locale = new java.util.Locale("zh", "CN");setting.setLocale(locale);setting.setEncoding("ISO-8859-1");// 创建工作薄work = Workbook.createWorkbook(os); // 建立excel文件// 创建第一个工作表jxl.write.WritableSheet ws = work.createSheet(sheetName, 1); // sheet名称// 添加标题addColumNameToWsheet(ws);List<User> list = (List<User>) map.get("list");writeContext(ws, list);} catch (Exception e) {e.printStackTrace();} finally {// 写入文件try {work.write();work.close();os.flush();os.close();} catch (WriteException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}private <T> void writeContext(WritableSheet wsheet, List<T> list) {int rows = list.size();jxl.write.Label wlabel = null;jxl.write.WritableCellFormat wcf = getFormat();int cols = dbColumnNames.length;String columnName = null;Object value = null;try {for (int i = 0; i < rows; i++) {T t = (T) list.get(i);              for (int j = 0; j < cols; j++) {columnName = dbColumnNames[j].toLowerCase();value = PropertyUtils.getProperty(t, columnName);wlabel = new jxl.write.Label(j, (i + 1), value + "", wcf);wlabel = new jxl.write.Label(j, (i + 1), value + "");wsheet.addCell(wlabel);}}} catch (Exception e) {e.printStackTrace();}}// 添加标题样式private void addColumNameToWsheet(jxl.write.WritableSheet wsheet)throws RowsExceededException, WriteException {// 设置excel标题jxl.write.WritableFont wfont = getFont();if (null == wfont) {wfont = new WritableFont(WritableFont.ARIAL,WritableFont.DEFAULT_POINT_SIZE, WritableFont.BOLD);}jxl.write.WritableCellFormat wcfFC = getFormat();if (null == wcfFC) {wcfFC = new jxl.write.WritableCellFormat(wfont);try {wcfFC.setWrap(true);// 自动换行wcfFC.setAlignment(Alignment.CENTRE);wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);// 设置对齐方式} catch (WriteException e) {e.printStackTrace();}}jxl.write.Label wlabel1 = null;String[] columNames = columnNames;if (null == columNames)return;int colSize = columNames.length;Integer[] colsWidth = columnWidths;if (null == colsWidth) {colsWidth = new Integer[colSize];for (int i = 0; i < colSize; i++) {colsWidth[i] = 20;}}int temp = 0;String colName = null;for (int i = 0; i < colSize; i++) {colName = columNames[i];if (null == colName || "".equals(colName))colName = "";wlabel1 = new jxl.write.Label(i, 0, colName, wcfFC);wsheet.addCell(wlabel1);temp = colsWidth[i].intValue();// 默认设置列宽temp = temp == 0 ? 20 : temp;wsheet.setColumnView(i, temp);}}// 设置格式private WritableCellFormat getFormat() {jxl.write.WritableFont wfont = getFont();jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(wfont);try {wcfFC.setWrap(true);wcfFC.setAlignment(Alignment.CENTRE);wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);} catch (WriteException e) {e.printStackTrace();}return wcfFC;}// 设置字体private WritableFont getFont() {return new WritableFont(WritableFont.ARIAL,WritableFont.DEFAULT_POINT_SIZE, WritableFont.BOLD);}}

4 ViewExcel.java

Java代码 复制代码 收藏代码
  1. package com.liuzd.sj.web;
  2. import java.net.URLEncoder;
  3. import java.util.Iterator;
  4. import java.util.List;
  5. import java.util.Map;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  9. import org.apache.poi.hssf.usermodel.HSSFDataFormat;
  10. import org.apache.poi.hssf.usermodel.HSSFRow;
  11. import org.apache.poi.hssf.usermodel.HSSFSheet;
  12. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  13. import org.springframework.web.servlet.view.document.AbstractExcelView;
  14. import com.liuzd.sj.entity.Student;
  15. /**
  16. * 生成excel视图,可用excel工具打开或者保存
  17. * 由ViewController的return new ModelAndView(viewExcel, model)生成
  18. */
  19. public class ViewExcel extends AbstractExcelView {
  20. public void buildExcelDocument(Map model, HSSFWorkbook workbook,
  21. HttpServletRequest request, HttpServletResponse response)
  22. throws Exception {
  23. String excelName = "用户信息.xls";
  24. // 设置response方式,使执行此controller时候自动出现下载页面,而非直接使用excel打开
  25. response.setContentType("APPLICATION/OCTET-STREAM");
  26. response.setHeader("Content-Disposition""attachment; filename="+ URLEncoder.encode(excelName, "UTF-8"));
  27. List stuList = (List) model.get("list");
  28. // 产生Excel表头
  29. HSSFSheet sheet = workbook.createSheet("studentList");
  30. HSSFRow header = sheet.createRow(0); // 第0行
  31. // 产生标题列
  32. header.createCell((short0).setCellValue("name");
  33. header.createCell((short1).setCellValue("sex");
  34. header.createCell((short2).setCellValue("date");
  35. header.createCell((short3).setCellValue("count");
  36. HSSFCellStyle cellStyle = workbook.createCellStyle();
  37. cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("mm/dd/yyyy"));
  38. // 填充数据
  39. int rowNum = 1;
  40. for (Iterator iter = stuList.iterator(); iter.hasNext();) {
  41. Student element = (Student) iter.next();
  42. HSSFRow row = sheet.createRow(rowNum++);
  43. row.createCell((short0)
  44. .setCellValue(element.getName().toString());
  45. row.createCell((short1).setCellValue(element.getSex().toString());
  46. row.createCell((short2)
  47. .setCellValue(element.getDate().toString());
  48. row.getCell((short2).setCellStyle(cellStyle);
  49. row.createCell((short3).setCellValue(element.getCount());
  50. }
  51. // 列总和计算
  52. HSSFRow row = sheet.createRow(rowNum);
  53. row.createCell((short0).setCellValue("TOTAL:");
  54. String formual = "SUM(D2:D" + rowNum + ")"// D2到D[rowNum]单元格起(count数据)
  55. row.createCell((short3).setCellFormula(formual);
  56. }
  57. }
package com.liuzd.sj.web;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;import com.liuzd.sj.entity.Student;
/**
* 生成excel视图,可用excel工具打开或者保存
* 由ViewController的return new ModelAndView(viewExcel, model)生成
*/
public class ViewExcel extends AbstractExcelView {   public void buildExcelDocument(Map model, HSSFWorkbook workbook,   HttpServletRequest request, HttpServletResponse response)   throws Exception {  String excelName = "用户信息.xls";// 设置response方式,使执行此controller时候自动出现下载页面,而非直接使用excel打开response.setContentType("APPLICATION/OCTET-STREAM");response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(excelName, "UTF-8"));  List stuList = (List) model.get("list");   // 产生Excel表头HSSFSheet sheet = workbook.createSheet("studentList");HSSFRow header = sheet.createRow(0); // 第0行// 产生标题列header.createCell((short) 0).setCellValue("name");header.createCell((short) 1).setCellValue("sex");header.createCell((short) 2).setCellValue("date");header.createCell((short) 3).setCellValue("count");HSSFCellStyle cellStyle = workbook.createCellStyle();cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("mm/dd/yyyy"));// 填充数据int rowNum = 1;for (Iterator iter = stuList.iterator(); iter.hasNext();) {Student element = (Student) iter.next();HSSFRow row = sheet.createRow(rowNum++);row.createCell((short) 0).setCellValue(element.getName().toString());row.createCell((short) 1).setCellValue(element.getSex().toString());row.createCell((short) 2).setCellValue(element.getDate().toString());row.getCell((short) 2).setCellStyle(cellStyle);row.createCell((short) 3).setCellValue(element.getCount());}// 列总和计算HSSFRow row = sheet.createRow(rowNum);row.createCell((short) 0).setCellValue("TOTAL:");String formual = "SUM(D2:D" + rowNum + ")"; // D2到D[rowNum]单元格起(count数据)row.createCell((short) 3).setCellFormula(formual);}
}

5 ViewPDF.java

Java代码 复制代码 收藏代码
  1. package com.liuzd.sj.web;
  2. import java.net.URLEncoder;
  3. import java.util.List;
  4. import java.util.Map;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import org.springframework.web.servlet.view.document.AbstractPdfView;
  8. import com.liuzd.sj.entity.Student;
  9. import com.lowagie.text.Document;
  10. import com.lowagie.text.Paragraph;
  11. import com.lowagie.text.pdf.BaseFont;
  12. import com.lowagie.text.pdf.PdfWriter;
  13. /**
  14. * 生成PDF视图,可用PDF浏览器打开或者保存
  15. * 由ViewController的return new ModelAndView(viewPDF, model)生成
  16. * @version Version 1.0
  17. */
  18. public class ViewPDF extends AbstractPdfView {
  19. public void buildPdfDocument(Map model, Document document,
  20. PdfWriter writer, HttpServletRequest request,
  21. HttpServletResponse response) throws Exception {
  22. String excelName = "用户信息.pdf";
  23. // 设置response方式,使执行此controller时候自动出现下载页面,而非直接使用excel打开
  24. response.setContentType("APPLICATION/OCTET-STREAM");
  25. response.setHeader("Content-Disposition""attachment; filename="+ URLEncoder.encode(excelName, "UTF-8"));
  26. List stuList = (List) model.get("list");
  27. //显示中文
  28. BaseFont bfChinese = BaseFont.createFont("STSong-Light""UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
  29. com.lowagie.text.Font FontChinese = new com.lowagie.text.Font(bfChinese, 12, com.lowagie.text.Font.NORMAL );
  30. String value = null;
  31. for (int i = 0; i < stuList.size(); i++) {
  32. Student s = (Student)stuList.get(i);
  33. value = "姓名: "+ s.getName()+",性别: "+s.getSex() + ",日期: " + s.getDate() + ",总数: " + s.getCount();
  34. document.add(new Paragraph(value,FontChinese));
  35. }
  36. }
  37. }
package com.liuzd.sj.web;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.view.document.AbstractPdfView;import com.liuzd.sj.entity.Student;
import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;
/**
* 生成PDF视图,可用PDF浏览器打开或者保存
* 由ViewController的return new ModelAndView(viewPDF, model)生成
* @version Version 1.0
*/
public class ViewPDF extends AbstractPdfView {   public void buildPdfDocument(Map model, Document document,   PdfWriter writer, HttpServletRequest request,   HttpServletResponse response) throws Exception {   String excelName = "用户信息.pdf";// 设置response方式,使执行此controller时候自动出现下载页面,而非直接使用excel打开response.setContentType("APPLICATION/OCTET-STREAM");response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(excelName, "UTF-8")); List stuList = (List) model.get("list");          //显示中文BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); com.lowagie.text.Font FontChinese = new com.lowagie.text.Font(bfChinese, 12, com.lowagie.text.Font.NORMAL );       String value = null;for (int i = 0; i < stuList.size(); i++) {  Student s = (Student)stuList.get(i);value = "姓名: "+ s.getName()+",性别: "+s.getSex() + ",日期: " + s.getDate() + ",总数: " + s.getCount();document.add(new Paragraph(value,FontChinese));   }}
}

6 springmvc.xml

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:p="http://www.springframework.org/schema/p"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:mvc="http://www.springframework.org/schema/mvc"
  7. xsi:schemaLocation="
  8. http://www.springframework.org/schema/beans
  9. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  12. http://www.springframework.org/schema/mvc
  13. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
  14. <!--
  15. 自动搜索@Controller标注的类
  16. 用于指明系统从哪个路径下寻找controller,然后提前初始化这些对象。
  17. -->
  18. <context:component-scan base-package="com.liuzd.sj.web" />
  19. <mvc:annotation-driven/>
  20. <!--  ③:对模型视图名称的解析,即在模型视图名称添加前后缀 -->
  21. <bean
  22. class="org.springframework.web.servlet.view.InternalResourceViewResolver"
  23. p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
  24. </beans>
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/mvc    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"><!-- 自动搜索@Controller标注的类用于指明系统从哪个路径下寻找controller,然后提前初始化这些对象。--><context:component-scan base-package="com.liuzd.sj.web" />  <mvc:annotation-driven/>          <!--  ③:对模型视图名称的解析,即在模型视图名称添加前后缀 --><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> </beans>

三 附件为工程源代码http://dl.iteye.com/topics/download/23bd290d-405a-3e9b-b557-28c3773bdeb3
四 相关jar包下载
jackson-all-1.8.1.jar请参见:SpringMVC:整合JQUERY与JSON
http://liuzidong.iteye.com/blog/1069343
jexcelapi_2_6_12_1.jar
http://dl.iteye.com/topics/download/4662fd6c-4dee-3dba-ac12-509ff9323258
iText-POI.zip中包含jar包有:iText-2.1.2.jar,iTextAsian.jar,poi-3.7-20101029.jar
http://dl.iteye.com/topics/download/a919b53f-615d-3b67-b790-32b4e0fec85f

用spring MVC 生成Excel和PDF相关推荐

  1. Jett+Spring MVC实现Excel导出

    接上文,由于本人在使用Jxls进行Excel导出时遇到数据遍历时Shift Row的格式问题无法解决,同时项目又较为紧张,于是尝试了使用Jett,幸好该框架基本能满足本人的需求,同时感觉各项功能的支持 ...

  2. Swagger+Spring mvc生成Restful接口文档

    2019独角兽企业重金招聘Python工程师标准>>> Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.总体目标是使客户端 ...

  3. Spring MVC生成PDF文件代码示例

    以下示例演示如何使用Spring Web MVC框架生成PDF格式的文件.首先使用Eclipse IDE,并按照以下步骤使用Spring Web Framework开发基于动态表单的Web应用程序: ...

  4. Spring MVC 实现Excel的导入导出功能(2:Excel的导入优化和Excel的导出)

    Excel的导入V2优化版 有些时候文件上传这一步骤由前端来处理,只将上传后的 URL 传输给后端(可以参考上一文中的图片上传功能),也就是导入请求中并不会直接处理 MultipartFile 对象, ...

  5. Spring MVC 生成文件类型响应

    图片控制器代码如下: @Controller @RequestMapping("/") public class WebController {@RequestMapping(me ...

  6. java读取excrl模板填充数据,spring mvc 读取excel模板填充数据下载

    需求: 将订单信息导出到excel中,存在excel模板,需要向其中添加数据. 技术选型: 对于excel操作,使用apache poi包.到maven repository找poi最新的发行包. 搜 ...

  7. java操作Excel、PDF文件

    java操作Excel.PDF文件 下面这些是在开发中用到的一些东西,有的代码贴的不是完整的,只是贴出了关于操作EXCEL的代码: jxl是一个*国人写的java操作excel的工具, 在开源世界中, ...

  8. 菜鸟关于mvc导出Excel的想法

    本人菜鸟一个,关于MVC生成Excel的一点想法.有错误请指教. 在视图上最终生成的table.添加下载excel按钮,用js或jq写当点击这个按钮执行查找页面上的<table>标签,并提 ...

  9. java架构-Spring MVC 与 Servlet

    相信大家都能够在上网上看到Spring MVC的核心类其实就是DispatherServlet,也就是Spring MVC处理请求的核心分发器.其实核心分发器几乎是所有MVC框架设计中的核心概念,像在 ...

  10. iReport制作EXCEL、PDF或者HTML文件

    公司用到了iReport制作报表,正好,毕业论文上也得用到报表,也就稍稍学习了下.个人感觉还是有个人教你的话,这个入门的最佳捷径. 一.首先是下载iReport,我下载的是iReport-5.1.0, ...

最新文章

  1. 使用阿里云服务器安装docker,并用nginx示例
  2. Linux 内核,30 年C 语言将升级至 C11
  3. 冬天了,麦克风/话筒 有杂音 的原因!
  4. java的单例设计模式
  5. aptio setup utility怎么设置u盘启动_CentOS 7下载及系统U盘制作
  6. nand ubi -3 uboot和ubi
  7. python django用户登录系统_Django实现用户注册登录
  8. wat java_并发工具优于wati、notify(69)
  9. 1.C#基础之简介(完成)
  10. 【转】Unix系统的心脏-Unix文件系统
  11. Apache 安全配置方法
  12. 性能测试 - 响应 vs 延迟 vs 吞吐量 vs 负载 vs 扩展性 vs 压力 vs 健壮性
  13. 阶段5 3.微服务项目【学成在线】_day04 页面静态化_10-freemarker静态化测试-基于模板文件静态化...
  14. hex2bin 64bit
  15. Vue - 最新网页 H5 分享到微信朋友圈 / 转发分享给朋友好友 / 分享到手机 QQ / 分享到 QQ 空间,Vue.js Nuxt.js uni-app 通用公众号页面解决方案(超级详细教程)
  16. 为什么qq相册显示服务器数据错误,玩qq空间常遇到的问题及解决办法_qq空间
  17. 卡内基梅隆大学计算机专业系,卡内基梅隆大学计算机
  18. UOJ14 DZY Loves Graph
  19. 阿里云服务器端口访问失败 问题解决
  20. BZOJ-1076: [SCOI2008]奖励关 (概率期望DP 未完待续)

热门文章

  1. 微信\支付宝扫码条码区分规则
  2. pandas 排序 excel
  3. 第四次实验任务 任务一
  4. 平面向量内积坐标公式推导_平面向量内积的坐标运算与距离公式
  5. Python-Numpy练习
  6. ld链接动态库静态库问题
  7. 计算机为啥启用不了网络发现,Windows7系统无法启用网络发现怎么解决?
  8. 杭电ACM-LCY算法进阶培训班-专题训练(Hash及其应用)
  9. 什么是数据库存储过程?
  10. 英语听力学习-VOA