服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Spring 实现excel及pdf导出表格示例

Spring 实现excel及pdf导出表格示例

2020-09-03 13:36DFDHZ Java教程

本篇文章主要介绍了Spring 实现excel及pdf导出表格示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

整理文档,搜刮出一个Spring 实现excel及pdf导出表格的代码,稍微整理精简一下做下分享。

excel 导出:

  1. package light.mvc.utils.excel; 
  2.   
  3. import java.util.Date; 
  4. import java.util.List; 
  5. import java.util.Map; 
  6.   
  7. import javax.servlet.http.HttpServletRequest; 
  8. import javax.servlet.http.HttpServletResponse; 
  9.   
  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.HSSFSheet; 
  14. import org.apache.poi.hssf.usermodel.HSSFWorkbook; 
  15. import org.springframework.web.servlet.view.document.AbstractExcelView; 
  16.   
  17. import light.mvc.pageModel.sys.Log; 
  18. import light.mvc.utils.Tools; 
  19.   
  20.   
  21. public class ExcelView extends AbstractExcelView{ 
  22.     
  23.   private HSSFSheet sheet; 
  24.   private HSSFCell cell; 
  25.   
  26.   @Override 
  27.   protected void buildExcelDocument(Map<String, Object> model, 
  28.       HSSFWorkbook workbook, HttpServletRequest request, 
  29.       HttpServletResponse response) throws Exception { 
  30.     // TODO Auto-generated method stub 
  31.     Date date = new Date(); 
  32.     String filename = Tools.date2Str(date, "yyyyMMddHHmmss"); 
  33.     String title_content = (String) model.get("title_content"); 
  34.     response.setContentType("application/octet-stream"); 
  35.     response.setHeader("Content-Disposition""attachment;filename="+filename+".xls"); 
  36.     sheet = workbook.createSheet(title_content); 
  37.       
  38.     List<String> titles = (List<String>) model.get("titles"); 
  39.     int len = titles.size(); 
  40.     HSSFCellStyle headerStyle = workbook.createCellStyle(); //标题样式 
  41.     headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); 
  42.     headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); 
  43.     HSSFFont headerFont = workbook.createFont();  //标题字体 
  44.     headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); 
  45.     headerFont.setFontHeightInPoints((short)11); 
  46.     headerStyle.setFont(headerFont); 
  47.     short width = 20,height=25*20; 
  48.     sheet.setDefaultColumnWidth(width); 
  49.     for(int i=0; i<len; i++){ //设置标题 
  50.       String title = titles.get(i); 
  51.       cell = getCell(sheet, 0, i); 
  52.       cell.setCellStyle(headerStyle); 
  53.       setText(cell,title); 
  54.     } 
  55.     sheet.getRow(0).setHeight(height); 
  56.       
  57.     HSSFCellStyle contentStyle = workbook.createCellStyle(); //内容样式 
  58.     contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); 
  59.     String type = (String) model.get("type"); 
  60.     if ("log".equals(type)){ 
  61.       List<Log> logList = (List<Log>) model.get("list"); 
  62.       logExcel(logList, contentStyle); 
  63.     } 
  64.       
  65.   } 
  66.   /** 
  67.    * 
  68.   * @Title: logExcel 
  69.   * @Description: 日志导出 
  70.   * @param @param logList 
  71.   * @param @param contentStyle 
  72.   * @return void 
  73.   * @throws 
  74.    */ 
  75.   public void logExcel(List<Log> logList, HSSFCellStyle contentStyle){ 
  76.     int logCount = logList.size(); 
  77.     if (logList != null && logCount > 0){ 
  78.       for(int i=0; i<logCount; i++){ 
  79.         Log log = logList.get(i); 
  80.         String loginname = log.getLoginname(); 
  81.         cell = getCell(sheet, i+1, 0); 
  82.         cell.setCellStyle(contentStyle); 
  83.         setText(cell,loginname); 
  84.           
  85.         String username = log.getName(); 
  86.         cell = getCell(sheet, i+1, 1); 
  87.         cell.setCellStyle(contentStyle); 
  88.         setText(cell,username); 
  89.           
  90.         String IP = log.getIp(); 
  91.         cell = getCell(sheet, i+1, 2); 
  92.         cell.setCellStyle(contentStyle); 
  93.         setText(cell,IP); 
  94.           
  95.         String organizationName = log.getOrganizationName(); 
  96.         cell = getCell(sheet, i+1, 3); 
  97.         cell.setCellStyle(contentStyle); 
  98.         setText(cell,organizationName); 
  99.           
  100.         String usertype = log.getUsertype()==0 ? "管理员" : "员工"
  101.         cell = getCell(sheet, i+1, 4); 
  102.         cell.setCellStyle(contentStyle); 
  103.         setText(cell,usertype); 
  104.           
  105.         String msg = log.getMsg(); 
  106.         cell = getCell(sheet, i+1, 5); 
  107.         cell.setCellStyle(contentStyle); 
  108.         setText(cell,msg); 
  109.           
  110.         Date lastLogin = log.getCreatedatetime()!=null ? log.getCreatedatetime() : null;  
  111.         cell = getCell(sheet, i+1, 6); 
  112.         cell.setCellStyle(contentStyle); 
  113.         setText(cell,Tools.date2Str(lastLogin)); 
  114.       } 
  115.     } 
  116.   } 

pdf导出:

重写spring调用itext

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package light.mvc.utils.pdf;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.AbstractView; 
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
 
/**
 * 这里就全部复制spring 的,然后引入的东西改成第5版的就行了 代码 几乎不变,唯一变的是引用路径~。
 *
 *
 */
public abstract class AbstractIText5PdfView extends AbstractView {
  public AbstractIText5PdfView() {
    setContentType("application/pdf");
  }
 
  @Override
  protected boolean generatesDownloadContent() {
    return true;
  }
 
  @Override
  protected final void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
      HttpServletResponse response) throws Exception {
    // 获得流
    ByteArrayOutputStream baos = createTemporaryOutputStream();
    Document document = newDocument();
    PdfWriter writer = newWriter(document, baos);
    prepareWriter(model, writer, request);
    buildPdfMetadata(model, document, request);
    document.open();
    buildPdfDocument(model, document, writer, request, response);
    document.close();
    writeToResponse(response, baos);
  }
 
  protected Document newDocument() {
    return new Document(PageSize.A4);
  }
 
  protected PdfWriter newWriter(Document document, OutputStream os) throws DocumentException {
    return PdfWriter.getInstance(document, os);
  }
 
  protected void prepareWriter(Map<String, Object> model, PdfWriter writer, HttpServletRequest request)
      throws DocumentException {
 
    writer.setViewerPreferences(getViewerPreferences());
  }
 
  protected int getViewerPreferences() {
    return PdfWriter.ALLOW_PRINTING | PdfWriter.PageLayoutSinglePage;
  }
 
  protected void buildPdfMetadata(Map<String, Object> model, Document document, HttpServletRequest request) {
  }
 
  protected abstract void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer,
      HttpServletRequest request, HttpServletResponse response) throws Exception;
}

pdf 公共类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package light.mvc.utils.pdf;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
import com.itextpdf.text.Chunk;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
 
/**
* @ClassName: PDFUtil
* @Description:
* @author liuyajun
* @date 2017年3月2日 下午1:21:21
*
*/
public class PDFUtil {
  // 对参数的封装形式比如{name}
  public static final String BEGIN = "{";
  public static final String END = "}";
  // 换行形式{#}
  public static final String NEW_LINE = "#";
  // 默认的行间距、首行距离等,自己添加
  public static final float DEFAULT_LEADING = 20;
  public static final float DEFAULT_LINE_INDENT = 30;
   
   
  // 基本字体和样式
  public static BaseFont bfChinese;
  public static Font fontChinese;
  public static Font UNDER_LINE = null;
  static{
    try {
      // SIMKAI.TTF 默认系统语言,这里没使用第三方语言包
      bfChinese = BaseFont.createFont("D:/home/java/contract/web/fonts/simsun.ttf",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
      //bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
       
      fontChinese = new Font(bfChinese, 12, Font.NORMAL);
      UNDER_LINE = new Font(bfChinese, 14,Font.UNDERLINE);
    } catch (DocumentException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
    
  // 默认样式
  public static Paragraph getParagraph(String context){
    return getParagraph(context,fontChinese);
  }
   
  public static Paragraph getParagraph(Chunk chunk){
    return new Paragraph(chunk);
  }
   
  // 指定字体样式
  public static Paragraph getParagraph(String context,Font font){
    return new Paragraph(context,font);
  }
   
  // 获得新行,首行缩进,和行间距
  public static Paragraph getNewParagraph(String context,float fixedLeading,float firstLineIndent){
    Paragraph p = getParagraph(context);
    p.setLeading(fixedLeading);
    p.setFirstLineIndent(firstLineIndent);
    return p;
  }
   
   public static Paragraph getParagraph(String content , Font font , float fixedLeading , int alignment){ 
     Paragraph p = getParagraph(content);
     p.setFont(font);
     p.setLeading(fixedLeading);
     p.setAlignment(alignment);
     return p; 
   }
   
  // 默认段落样式
  public static Paragraph getDefaultParagraph(String context){
    Paragraph p = getParagraph(context);
    // 默认行间距
    p.setLeading(DEFAULT_LEADING);
    // 默认首行空隙
    p.setFirstLineIndent(DEFAULT_LINE_INDENT);
    return p;
  }
   
  // 将参数和字符串内容组合成集合
  public static List<Paragraph> createParagraphs(String context ,Map<String,Object> map){
    int index = 0;
    List<Paragraph> list = new ArrayList<Paragraph>();
    Paragraph p = getDefaultParagraph(null);
    while((index = context.indexOf(BEGIN)) > -1){
      String text = context.substring(0,index);
      context = context.substring(index, context.length());
      index = context.indexOf(END);
      String param = null;
      if(index > 0){
         param = context.substring(BEGIN.length(),index);
      }
      p.add(text);
      if(!NEW_LINE.equals(param)){
        Object value = map.get(param);
        if(value != null){
          p.add(new Chunk(value.toString(),UNDER_LINE));
        }else{
          p.add(new Chunk(""));
        }
      }else{
        list.add(p);
        p = getDefaultParagraph(null);
        p.setSpacingBefore(0);
      }
      context = context.substring(index+END.length(),context.length());
    }
    list.add(p);
    list.add(getParagraph(context));
    return list;
  }
}

生成pdf

  1. package light.mvc.utils.pdf; 
  2.   
  3. import java.util.Date; 
  4. import java.util.List; 
  5. import java.util.Map; 
  6.   
  7. import javax.servlet.http.HttpServletRequest; 
  8. import javax.servlet.http.HttpServletResponse; 
  9.   
  10. import com.itextpdf.text.Chunk; 
  11. import com.itextpdf.text.Document; 
  12. import com.itextpdf.text.Font; 
  13. import com.itextpdf.text.Paragraph; 
  14. import com.itextpdf.text.pdf.PdfPTable; 
  15. import com.itextpdf.text.pdf.PdfWriter; 
  16.   
  17. import light.mvc.pageModel.sys.Log; 
  18. import light.mvc.utils.Tools; 
  19.   
  20. /** 
  21. * @ClassName: LogPdfView 
  22. * @Description: 
  23. * @author liuyajun 
  24. * @date 2017年3月2日 上午11:18:44 
  25. * 
  26. */ 
  27. public class PdfView extends AbstractIText5PdfView{ 
  28.   
  29.   @Override 
  30.   protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer,  
  31.       HttpServletRequest request, HttpServletResponse response) throws Exception { 
  32.     try{  
  33.       document.open();  
  34.       // 标题居中  
  35.       String title_content = (String) model.get("title_content"); 
  36.       Paragraph title = PDFUtil.getParagraph(  
  37.             new Chunk(title_content,new Font(PDFUtil.bfChinese,16,Font.BOLD)));  
  38.       title.setAlignment(Paragraph.ALIGN_CENTER);  
  39.       document.add(title);  
  40.          
  41.       // 表格标题  
  42.       List<String> titles = (List<String>) model.get("titles"); 
  43.       int len = titles.size(); 
  44.       PdfPTable table = new PdfPTable(len);  
  45.       table.setSpacingBefore(20);  
  46.       table.setSpacingAfter(30);  
  47.       for(int i=0; i<len; i++){ //设置标题 
  48.         String str = titles.get(i); 
  49.         table.addCell(PDFUtil.getParagraph(str));  
  50.       } 
  51.         
  52.       // 表格数据  
  53.       String type = (String) model.get("type"); 
  54.       if ("log".equals(type)){ 
  55.         List<Log> logList = (List<Log>) model.get("list");  
  56.         table = logPdf(table, logList); 
  57.       } 
  58.         
  59.       document.add(table);  
  60.       // 关闭  
  61.       document.close();  
  62.     }catch (Exception e) {  
  63.       e.printStackTrace();  
  64.     }  
  65.       
  66.   } 
  67.     
  68.   /** 
  69.    * 
  70.   * @Title: logPdf 
  71.   * @Description: 日志导出 
  72.   * @param @param table 
  73.   * @param @param logList 
  74.   * @param @return 
  75.   * @return PdfPTable 
  76.   * @throws 
  77.    */ 
  78.   public PdfPTable logPdf(PdfPTable table, List<Log> logList){ 
  79.     int logCount = logList.size(); 
  80.     if (logList != null && logCount > 0){ 
  81.       for(int i=0; i<logCount; i++){ 
  82.         Log log = logList.get(i); 
  83.         String loginname = log.getLoginname(); 
  84.         table.addCell(PDFUtil.getParagraph(loginname));  
  85.           
  86.         String username = log.getName(); 
  87.         table.addCell(PDFUtil.getParagraph(username)); 
  88.           
  89.         String IP = log.getIp(); 
  90.         table.addCell(PDFUtil.getParagraph(IP)); 
  91.           
  92.         String organizationName = log.getOrganizationName(); 
  93.         table.addCell(PDFUtil.getParagraph(organizationName)); 
  94.           
  95.         String usertype = log.getUsertype()==0 ? "管理员" : "员工"
  96.         table.addCell(PDFUtil.getParagraph(usertype)); 
  97.           
  98.         String msg = log.getMsg(); 
  99.         table.addCell(PDFUtil.getParagraph(msg)); 
  100.           
  101.         Date lastLogin = log.getCreatedatetime()!=null ? log.getCreatedatetime() : null
  102.         table.addCell(PDFUtil.getParagraph(Tools.date2Str(lastLogin))); 
  103.       } 
  104.     } 
  105.     return table; 
  106.       
  107.   } 
  108.   
 

调用

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
   * 导出用户信息到excel/pdf
   * @return
   */
  @RequestMapping("/download")
  public ModelAndView export2Excel(HttpServletRequest request, Log log){
    SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute(GlobalConstant.SESSION_INFO);
    if (!"admin".equals(sessionInfo.getLoginname())){
      log.setUsertype(1);
      log.setOrganizationId(sessionInfo.getOrganizationid());
    }
    if ("1".equals(sessionInfo.getUsertype())){
      log.setLoginname(sessionInfo.getLoginname());
    }
    PageFilter ph = new PageFilter();
    ph.setSort("createdatetime");
    ph.setOrder("desc");
    List<Log> list = logService.dataGrid(log, ph);
    Map<String,Object> dataMap = new HashMap<String,Object>();
    List<String> titles = new ArrayList<String>();
    titles.add("登录名");
    titles.add("姓名");
    titles.add("IP地址");
    titles.add("所属部门");
    titles.add("用户类型");
    titles.add("操作内容");
    titles.add("操作时间");
    dataMap.put("titles", titles);
    dataMap.put("list", list);
    dataMap.put("title_content", "日志");
    dataMap.put("type", "log");
    String str = request.getParameter("str");
    ModelAndView mv = null;
    if ("excel".equals(str)){
      ExcelView excel = new ExcelView();
      mv = new ModelAndView(excel,dataMap);
    } else if("pdf".equals(str)){
      PdfView pdf = new PdfView();
      mv = new ModelAndView(pdf,dataMap);
    }
    insertlog(request,"下载"+str+"文件",2);
    return mv;
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://blog.csdn.net/qq_30762453/article/details/60130222

延伸 · 阅读

精彩推荐