整理文档,搜刮出一个Spring 实现excel及pdf导出表格的代码,稍微整理精简一下做下分享。
excel 导出:
- packagelight.mvc.utils.excel;
- importjava.util.Date;
- importjava.util.List;
- importjava.util.Map;
- importjavax.servlet.http.HttpServletRequest;
- importjavax.servlet.http.HttpServletResponse;
- importorg.apache.poi.hssf.usermodel.HSSFCell;
- importorg.apache.poi.hssf.usermodel.HSSFCellStyle;
- importorg.apache.poi.hssf.usermodel.HSSFFont;
- importorg.apache.poi.hssf.usermodel.HSSFSheet;
- importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
- importorg.springframework.web.servlet.view.document.AbstractExcelView;
- importlight.mvc.pageModel.sys.Log;
- importlight.mvc.utils.Tools;
- publicclassExcelViewextendsAbstractExcelView{
- privateHSSFSheetsheet;
- privateHSSFCellcell;
- @Override
- protectedvoidbuildExcelDocument(Map<String,Object>model,
- HSSFWorkbookworkbook,HttpServletRequestrequest,
- HttpServletResponseresponse)throwsException{
- //TODOAuto-generatedmethodstub
- Datedate=newDate();
- Stringfilename=Tools.date2Str(date,"yyyyMMddHHmmss");
- Stringtitle_content=(String)model.get("title_content");
- response.setContentType("application/octet-stream");
- response.setHeader("Content-Disposition","attachment;filename="+filename+".xls");
- sheet=workbook.createSheet(title_content);
- List<String>titles=(List<String>)model.get("titles");
- intlen=titles.size();
- HSSFCellStyleheaderStyle=workbook.createCellStyle();//标题样式
- headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
- headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
- HSSFFontheaderFont=workbook.createFont();//标题字体
- headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
- headerFont.setFontHeightInPoints((short)11);
- headerStyle.setFont(headerFont);
- shortwidth=20,height=25*20;
- sheet.setDefaultColumnWidth(width);
- for(inti=0;i<len;i++){//设置标题
- Stringtitle=titles.get(i);
- cell=getCell(sheet,0,i);
- cell.setCellStyle(headerStyle);
- setText(cell,title);
- }
- sheet.getRow(0).setHeight(height);
- HSSFCellStylecontentStyle=workbook.createCellStyle();//内容样式
- contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
- Stringtype=(String)model.get("type");
- if("log".equals(type)){
- List<Log>logList=(List<Log>)model.get("list");
- logExcel(logList,contentStyle);
- }
- }
- /**
- *
- *@Title:logExcel
- *@Description:日志导出
- *@param@paramlogList
- *@param@paramcontentStyle
- *@returnvoid
- *@throws
- */
- publicvoidlogExcel(List<Log>logList,HSSFCellStylecontentStyle){
- intlogCount=logList.size();
- if(logList!=null&&logCount>0){
- for(inti=0;i<logCount;i++){
- Loglog=logList.get(i);
- Stringloginname=log.getLoginname();
- cell=getCell(sheet,i+1,0);
- cell.setCellStyle(contentStyle);
- setText(cell,loginname);
- Stringusername=log.getName();
- cell=getCell(sheet,i+1,1);
- cell.setCellStyle(contentStyle);
- setText(cell,username);
- StringIP=log.getIp();
- cell=getCell(sheet,i+1,2);
- cell.setCellStyle(contentStyle);
- setText(cell,IP);
- StringorganizationName=log.getOrganizationName();
- cell=getCell(sheet,i+1,3);
- cell.setCellStyle(contentStyle);
- setText(cell,organizationName);
- Stringusertype=log.getUsertype()==0?"管理员":"员工";
- cell=getCell(sheet,i+1,4);
- cell.setCellStyle(contentStyle);
- setText(cell,usertype);
- Stringmsg=log.getMsg();
- cell=getCell(sheet,i+1,5);
- cell.setCellStyle(contentStyle);
- setText(cell,msg);
- DatelastLogin=log.getCreatedatetime()!=null?log.getCreatedatetime():null;
- cell=getCell(sheet,i+1,6);
- cell.setCellStyle(contentStyle);
- setText(cell,Tools.date2Str(lastLogin));
- }
- }
- }
- }
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
- packagelight.mvc.utils.pdf;
- importjava.util.Date;
- importjava.util.List;
- importjava.util.Map;
- importjavax.servlet.http.HttpServletRequest;
- importjavax.servlet.http.HttpServletResponse;
- importcom.itextpdf.text.Chunk;
- importcom.itextpdf.text.Document;
- importcom.itextpdf.text.Font;
- importcom.itextpdf.text.Paragraph;
- importcom.itextpdf.text.pdf.PdfPTable;
- importcom.itextpdf.text.pdf.PdfWriter;
- importlight.mvc.pageModel.sys.Log;
- importlight.mvc.utils.Tools;
- /**
- *@ClassName:LogPdfView
- *@Description:
- *@authorliuyajun
- *@date2017年3月2日上午11:18:44
- *
- */
- publicclassPdfViewextendsAbstractIText5PdfView{
- @Override
- protectedvoidbuildPdfDocument(Map<String,Object>model,Documentdocument,PdfWriterwriter,
- HttpServletRequestrequest,HttpServletResponseresponse)throwsException{
- try{
- document.open();
- //标题居中
- Stringtitle_content=(String)model.get("title_content");
- Paragraphtitle=PDFUtil.getParagraph(
- newChunk(title_content,newFont(PDFUtil.bfChinese,16,Font.BOLD)));
- title.setAlignment(Paragraph.ALIGN_CENTER);
- document.add(title);
- //表格标题
- List<String>titles=(List<String>)model.get("titles");
- intlen=titles.size();
- PdfPTabletable=newPdfPTable(len);
- table.setSpacingBefore(20);
- table.setSpacingAfter(30);
- for(inti=0;i<len;i++){//设置标题
- Stringstr=titles.get(i);
- table.addCell(PDFUtil.getParagraph(str));
- }
- //表格数据
- Stringtype=(String)model.get("type");
- if("log".equals(type)){
- List<Log>logList=(List<Log>)model.get("list");
- table=logPdf(table,logList);
- }
- document.add(table);
- //关闭
- document.close();
- }catch(Exceptione){
- e.printStackTrace();
- }
- }
- /**
- *
- *@Title:logPdf
- *@Description:日志导出
- *@param@paramtable
- *@param@paramlogList
- *@param@return
- *@returnPdfPTable
- *@throws
- */
- publicPdfPTablelogPdf(PdfPTabletable,List<Log>logList){
- intlogCount=logList.size();
- if(logList!=null&&logCount>0){
- for(inti=0;i<logCount;i++){
- Loglog=logList.get(i);
- Stringloginname=log.getLoginname();
- table.addCell(PDFUtil.getParagraph(loginname));
- Stringusername=log.getName();
- table.addCell(PDFUtil.getParagraph(username));
- StringIP=log.getIp();
- table.addCell(PDFUtil.getParagraph(IP));
- StringorganizationName=log.getOrganizationName();
- table.addCell(PDFUtil.getParagraph(organizationName));
- Stringusertype=log.getUsertype()==0?"管理员":"员工";
- table.addCell(PDFUtil.getParagraph(usertype));
- Stringmsg=log.getMsg();
- table.addCell(PDFUtil.getParagraph(msg));
- DatelastLogin=log.getCreatedatetime()!=null?log.getCreatedatetime():null;
- table.addCell(PDFUtil.getParagraph(Tools.date2Str(lastLogin)));
- }
- }
- returntable;
- }
- }
调用
?
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
相关文章
猜你喜欢
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-25 55
-
2025-06-04 40
-
2025-05-27 90
-
2025-05-25 97
-
2025-05-29 26
热门评论