- 浏览: 853744 次
文章分类
- 全部博客 (365)
- java (124)
- spring mvc (21)
- spring (22)
- struts2 (6)
- jquery (27)
- javascript (24)
- mybatis/ibatis (8)
- hibernate (7)
- compass (11)
- lucene (26)
- flex (0)
- actionscript (0)
- webservice (8)
- rabbitMQ/Socket (15)
- jsp/freemaker (5)
- 数据库 (27)
- 应用服务器 (21)
- Hadoop (1)
- PowerDesigner (3)
- EJB (0)
- JPA (0)
- PHP (2)
- C# (0)
- .NET (0)
- html (2)
- xml (5)
- android (7)
- flume (1)
- zookeeper (0)
- 证书加密 (2)
- maven (1)
- redis (2)
- cas (11)
最新评论
-
zuxianghuang:
通过pom上传报错 Artifact upload faile ...
nexus上传了jar包.通过maven引用当前jar,不能取得jar的依赖 -
流年末年:
百度网盘的挂了吧???
SSO单点登录系列3:cas-server端配置认证方式实践(数据源+自定义java类认证) -
953434367:
UfgovDBUtil 是什么类
Java发HTTP POST请求(内容为xml格式) -
smilease:
帮大忙了,非常感谢
freemaker自动生成源代码 -
syd505:
十分感谢作者无私的分享,仔细阅读后很多地方得以解惑。
Nginx 反向代理、负载均衡、页面缓存、URL重写及读写分离详解
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
- <%@ 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>
- <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>
<%@ 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> <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
- 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);
- }
- }
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
- 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 };
- @Override
- public 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);
- }
- }
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 }; @Override public 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
- 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);
- }
- }
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
- 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));
- }
- }
- }
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 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.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd
- http://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/>
- <!-- ③:对模型视图名称的解析,即在模型视图名称添加前后缀 -->
- <bean
- class="org.springframework.web.servlet.view.InternalResourceViewResolver"
- p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
- </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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://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/> <!-- ③:对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="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
发表评论
-
jackson annotations注解详解
2015-01-13 11:34 18997官方WIKI:https://github.com/Fast ... -
Ehcache 整合Spring 使用页面、对象缓存
2012-11-02 19:56 1110Ehcache在很多项目中都出现过,用法也比较简 ... -
Spring 3.1 M1 中的缓存功能
2012-11-02 19:26 830本文转自:http://www.oschina.net/ ... -
深入剖析Spring Web源码(八) - 处理器映射,处理器适配器以及处理器的实现 - 基于简单控制器流程的实现
2012-10-31 13:37 13301.1.1.1 ... -
spring 源码 阅读 笔记 之 HandlerMapping
2012-10-31 12:59 1678SpringCVSBeanHTMLAnt ... -
spring mvc重复提交拦截器方法
2012-10-31 11:37 9018import javax.servlet.http.HttpS ... -
不重复配置——利用Spring通用化配置
2012-10-17 09:40 982还记得 如下这种配置吗: 1、struts2作用域 ... -
Ehcache 整合Spring 使用页面、对象缓存
2012-10-16 09:44 789Ehcache在很多项目中都出现过,用法也比较简单。一般的 ... -
SpringMVC文件上传 多文件
2012-10-15 17:27 7088必须明确告诉DispatcherServlet如何处理Mult ... -
Spring MVC 3.1新特性 生产者、消费者请求限定
2012-10-12 11:50 11516.6.5、生产者、消费者限定 6.6.5.1、基本概念 ... -
spring + mybatis 多数据源切换
2012-10-10 11:42 1563[代码] DbContextHold ... -
spring MVC 文件上传
2012-10-06 10:03 2073spring支持在网络应用程序处理文件上传,提供拔插的org. ... -
JasperReport与spring集成的三种方式
2012-09-26 17:29 1863最近要用JasperReport,试着和sprin ... -
Spring MVC+Jasper Report 及生成PDF的中文问题
2012-09-26 17:10 2先说两句报表框架的选择,JasperRepor ... -
Springmvc与jasperreport结合生成报表的一种方法
2012-09-26 16:42 1<script type="text/ja ... -
spring 3.1中的cache小结
2012-09-22 23:27 1017spring 3.1中有cache了,下 ... -
Spring MVC和Struts2的区别
2012-09-08 08:59 10371. 机制:spring mvc的入口是servlet,而st ... -
SpringMVC + spring3.1.1 + hibernate4.1.0 集成及常见问题总结
2012-06-19 17:34 1429一 开发环境 1、动态web工程 2、部分依赖 ... -
SpringMVC+FreeMarker实现半自动静态化
2012-06-14 13:53 2541感谢imyourgod的原贴http://to ... -
文件下载(只需要简单的四步),Java中都通用
2012-06-15 08:33 1228Javadownload文件下载Spring ...
相关推荐
这个例子展示了如何使用 Spring MVC 和相关的库(Apache POI 和 iText)来动态生成 Excel 和 PDF 文件,提供给用户下载。整个流程涉及到 Spring MVC 的配置、控制器的编写以及与第三方库的集成,实现了从数据到视图...
对于PDF和Excel格式的输出,Spring MVC可以通过Apache POI库来处理Excel,使用Flying Saucer或iText库来生成PDF。这些库能够将HTML内容转换为所需的格式,方便导出和下载。 总的来说,Spring MVC是Spring框架的重要...
在Spring MVC框架中,生成Excel和PDF文件是常见的需求,特别是在数据导出、报表生成或者文档分享场景下。本文将详细讲解如何利用Spring MVC结合开源库实现Excel和PDF的生成。 首先,我们要引入两个关键的库:Apache...
总结来说,Spring MVC结合Apache POI和iText库,可以方便地实现在Web应用中导出Excel和PDF表格的功能。这在数据展示、报告生成等方面非常有用,使得用户可以方便地下载和查看数据。通过自定义视图类和模型数据,可以...
在IT领域,Spring MVC作为Spring框架的一部分,是用于构建Web应用程序的强大工具,而JasperReport则是一款功能丰富的报表生成库,支持多种格式,如PDF、HTML、Excel等。本示例将探讨如何在Spring3 MVC项目中集成...
在Spring MVC Web应用程序中集成Jasper报表工具是一个常见的需求,以提供动态生成和展示各种复杂数据的报表。JasperReports是一款强大的开源报表库,能够帮助开发者创建、设计和展示多种格式的报表,如PDF、HTML、...
在使用easypoi库进行Java项目的Excel表格导入导出时,开发者需要重视其依赖的引入,理解各注解的用途,以及能够解决使用过程中可能出现的类找不到或者依赖冲突等错误。另外,合理使用文档资源,跟进库的版本更新,也...
Spring MVC是Spring框架的一部分,用于构建Web应用程序,而JasperReports是一个开源报告工具,用于生成静态和动态的业务报告。在这个项目中,开发者可能将JasperReports的功能与Spring MVC的控制器、服务和视图解析...
项目还涉及了Excel和PDF的导出功能,这对于生成报表或者数据备份非常实用。在Java中,可以使用Apache POI库来操作Excel文件,iText库来生成PDF文件。 导出Excel功能通常涉及到读取数据源,如数据库或文件,然后将...
总的来说,这个压缩包提供了一个使用Spring Boot实现的Excel到PDF转换服务的示例。开发者可以通过查看和运行源代码学习如何处理Excel文件,以及如何利用Spring Boot的特性来构建这样的转换工具。这可能涉及到Apache ...
在本项目中,JasperReport用于设计和生成报表模板,开发者可以使用iReport(版本5.6.0)这个图形化工具来设计复杂的报表布局。iReport提供了拖拽式界面,可以方便地添加表格、图表、文本等元素,同时支持SQL查询,...
Struts、Hibernate、Spring、JFreeChart以及Excel和PDF导出是Java开发中常见的技术,它们在企业级应用开发中有着广泛的应用。这些技术的整合能够构建出功能强大的Web应用程序,提供数据展示、数据处理以及文件导出等...
Struts、Hibernate、Spring、JFreeChart以及Excel和PDF导出是Java开发中的关键技术和库,它们在构建高效、可维护的企业级应用中扮演着重要角色。以下是对这些技术的详细说明: 1. **Struts**:Struts是Apache软件...
easypoi教程总结为我们提供了关于easypoi的详细使用教程,涵盖了Excel、Word、HTML、PDF等多种文档的导出和导入操作,以及与Spring MVC框架的集成。通过学习本教程,我们可以快速掌握easypoi的使用,并应用于实际...
尤其值得注意的是,SpringMVC与servlet和JSP的松耦合关系,使其能够轻松与各种视图技术集成,如Freemarker、Excel或PDF生成工具,极大地提升了Web应用的多样性和表现力。 #### Spring3.0MVC系列教程概览 该系列...
"ireport+springMVC 报表导出pdf excel"这个主题聚焦于如何利用iReport工具和SpringMVC框架来实现报表的PDF和Excel格式导出功能。下面我们将深入探讨这两个技术以及它们在报表生成中的应用。 首先,iReport是一款...