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

2025-05-29 0 72

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

excel 导出:

  1. packagelight.mvc.utils.excel;
  2. importjava.util.Date;
  3. importjava.util.List;
  4. importjava.util.Map;
  5. importjavax.servlet.http.HttpServletRequest;
  6. importjavax.servlet.http.HttpServletResponse;
  7. importorg.apache.poi.hssf.usermodel.HSSFCell;
  8. importorg.apache.poi.hssf.usermodel.HSSFCellStyle;
  9. importorg.apache.poi.hssf.usermodel.HSSFFont;
  10. importorg.apache.poi.hssf.usermodel.HSSFSheet;
  11. importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
  12. importorg.springframework.web.servlet.view.document.AbstractExcelView;
  13. importlight.mvc.pageModel.sys.Log;
  14. importlight.mvc.utils.Tools;
  15. publicclassExcelViewextendsAbstractExcelView{
  16. privateHSSFSheetsheet;
  17. privateHSSFCellcell;
  18. @Override
  19. protectedvoidbuildExcelDocument(Map<String,Object>model,
  20. HSSFWorkbookworkbook,HttpServletRequestrequest,
  21. HttpServletResponseresponse)throwsException{
  22. //TODOAuto-generatedmethodstub
  23. Datedate=newDate();
  24. Stringfilename=Tools.date2Str(date,"yyyyMMddHHmmss");
  25. Stringtitle_content=(String)model.get("title_content");
  26. response.setContentType("application/octet-stream");
  27. response.setHeader("Content-Disposition","attachment;filename="+filename+".xls");
  28. sheet=workbook.createSheet(title_content);
  29. List<String>titles=(List<String>)model.get("titles");
  30. intlen=titles.size();
  31. HSSFCellStyleheaderStyle=workbook.createCellStyle();//标题样式
  32. headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  33. headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  34. HSSFFontheaderFont=workbook.createFont();//标题字体
  35. headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  36. headerFont.setFontHeightInPoints((short)11);
  37. headerStyle.setFont(headerFont);
  38. shortwidth=20,height=25*20;
  39. sheet.setDefaultColumnWidth(width);
  40. for(inti=0;i<len;i++){//设置标题
  41. Stringtitle=titles.get(i);
  42. cell=getCell(sheet,0,i);
  43. cell.setCellStyle(headerStyle);
  44. setText(cell,title);
  45. }
  46. sheet.getRow(0).setHeight(height);
  47. HSSFCellStylecontentStyle=workbook.createCellStyle();//内容样式
  48. contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  49. Stringtype=(String)model.get("type");
  50. if("log".equals(type)){
  51. List<Log>logList=(List<Log>)model.get("list");
  52. logExcel(logList,contentStyle);
  53. }
  54. }
  55. /**
  56. *
  57. *@Title:logExcel
  58. *@Description:日志导出
  59. *@param@paramlogList
  60. *@param@paramcontentStyle
  61. *@returnvoid
  62. *@throws
  63. */
  64. publicvoidlogExcel(List<Log>logList,HSSFCellStylecontentStyle){
  65. intlogCount=logList.size();
  66. if(logList!=null&&logCount>0){
  67. for(inti=0;i<logCount;i++){
  68. Loglog=logList.get(i);
  69. Stringloginname=log.getLoginname();
  70. cell=getCell(sheet,i+1,0);
  71. cell.setCellStyle(contentStyle);
  72. setText(cell,loginname);
  73. Stringusername=log.getName();
  74. cell=getCell(sheet,i+1,1);
  75. cell.setCellStyle(contentStyle);
  76. setText(cell,username);
  77. StringIP=log.getIp();
  78. cell=getCell(sheet,i+1,2);
  79. cell.setCellStyle(contentStyle);
  80. setText(cell,IP);
  81. StringorganizationName=log.getOrganizationName();
  82. cell=getCell(sheet,i+1,3);
  83. cell.setCellStyle(contentStyle);
  84. setText(cell,organizationName);
  85. Stringusertype=log.getUsertype()==0?"管理员":"员工";
  86. cell=getCell(sheet,i+1,4);
  87. cell.setCellStyle(contentStyle);
  88. setText(cell,usertype);
  89. Stringmsg=log.getMsg();
  90. cell=getCell(sheet,i+1,5);
  91. cell.setCellStyle(contentStyle);
  92. setText(cell,msg);
  93. DatelastLogin=log.getCreatedatetime()!=null?log.getCreatedatetime():null;
  94. cell=getCell(sheet,i+1,6);
  95. cell.setCellStyle(contentStyle);
  96. setText(cell,Tools.date2Str(lastLogin));
  97. }
  98. }
  99. }
  100. }

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. packagelight.mvc.utils.pdf;
  2. importjava.util.Date;
  3. importjava.util.List;
  4. importjava.util.Map;
  5. importjavax.servlet.http.HttpServletRequest;
  6. importjavax.servlet.http.HttpServletResponse;
  7. importcom.itextpdf.text.Chunk;
  8. importcom.itextpdf.text.Document;
  9. importcom.itextpdf.text.Font;
  10. importcom.itextpdf.text.Paragraph;
  11. importcom.itextpdf.text.pdf.PdfPTable;
  12. importcom.itextpdf.text.pdf.PdfWriter;
  13. importlight.mvc.pageModel.sys.Log;
  14. importlight.mvc.utils.Tools;
  15. /**
  16. *@ClassName:LogPdfView
  17. *@Description:
  18. *@authorliuyajun
  19. *@date2017年3月2日上午11:18:44
  20. *
  21. */
  22. publicclassPdfViewextendsAbstractIText5PdfView{
  23. @Override
  24. protectedvoidbuildPdfDocument(Map<String,Object>model,Documentdocument,PdfWriterwriter,
  25. HttpServletRequestrequest,HttpServletResponseresponse)throwsException{
  26. try{
  27. document.open();
  28. //标题居中
  29. Stringtitle_content=(String)model.get("title_content");
  30. Paragraphtitle=PDFUtil.getParagraph(
  31. newChunk(title_content,newFont(PDFUtil.bfChinese,16,Font.BOLD)));
  32. title.setAlignment(Paragraph.ALIGN_CENTER);
  33. document.add(title);
  34. //表格标题
  35. List<String>titles=(List<String>)model.get("titles");
  36. intlen=titles.size();
  37. PdfPTabletable=newPdfPTable(len);
  38. table.setSpacingBefore(20);
  39. table.setSpacingAfter(30);
  40. for(inti=0;i<len;i++){//设置标题
  41. Stringstr=titles.get(i);
  42. table.addCell(PDFUtil.getParagraph(str));
  43. }
  44. //表格数据
  45. Stringtype=(String)model.get("type");
  46. if("log".equals(type)){
  47. List<Log>logList=(List<Log>)model.get("list");
  48. table=logPdf(table,logList);
  49. }
  50. document.add(table);
  51. //关闭
  52. document.close();
  53. }catch(Exceptione){
  54. e.printStackTrace();
  55. }
  56. }
  57. /**
  58. *
  59. *@Title:logPdf
  60. *@Description:日志导出
  61. *@param@paramtable
  62. *@param@paramlogList
  63. *@param@return
  64. *@returnPdfPTable
  65. *@throws
  66. */
  67. publicPdfPTablelogPdf(PdfPTabletable,List<Log>logList){
  68. intlogCount=logList.size();
  69. if(logList!=null&&logCount>0){
  70. for(inti=0;i<logCount;i++){
  71. Loglog=logList.get(i);
  72. Stringloginname=log.getLoginname();
  73. table.addCell(PDFUtil.getParagraph(loginname));
  74. Stringusername=log.getName();
  75. table.addCell(PDFUtil.getParagraph(username));
  76. StringIP=log.getIp();
  77. table.addCell(PDFUtil.getParagraph(IP));
  78. StringorganizationName=log.getOrganizationName();
  79. table.addCell(PDFUtil.getParagraph(organizationName));
  80. Stringusertype=log.getUsertype()==0?"管理员":"员工";
  81. table.addCell(PDFUtil.getParagraph(usertype));
  82. Stringmsg=log.getMsg();
  83. table.addCell(PDFUtil.getParagraph(msg));
  84. DatelastLogin=log.getCreatedatetime()!=null?log.getCreatedatetime():null;
  85. table.addCell(PDFUtil.getParagraph(Tools.date2Str(lastLogin)));
  86. }
  87. }
  88. returntable;
  89. }
  90. }

调用

?

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;

}

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

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Spring 实现excel及pdf导出表格示例 https://www.kuaiidc.com/117999.html

相关文章

发表评论
暂无评论