Spring 实现excel及pdf导出表格示例
整理文档,搜刮出一个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(Mapmodel,
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);
Listtitles=(List)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;ilogList=(List)model.get("list");
logExcel(logList,contentStyle);
}
}
/**
*
*@Title:logExcel
*@Description:日志导出
*@param@paramlogList
*@param@paramcontentStyle
*@returnvoid
*@throws
*/
publicvoidlogExcel(ListlogList,HSSFCellStylecontentStyle){
intlogCount=logList.size();
if(logList!=null&&logCount>0){
for(inti=0;i
pdf导出:
重写spring调用itext
packagelight.mvc.utils.pdf;
importjava.io.ByteArrayOutputStream;
importjava.io.OutputStream;
importjava.util.Map;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.springframework.web.servlet.view.AbstractView;
importcom.itextpdf.text.Document;
importcom.itextpdf.text.DocumentException;
importcom.itextpdf.text.PageSize;
importcom.itextpdf.text.pdf.PdfWriter;
/**
*这里就全部复制spring的,然后引入的东西改成第5版的就行了代码几乎不变,唯一变的是引用路径~。
*
*
*/
publicabstractclassAbstractIText5PdfViewextendsAbstractView{
publicAbstractIText5PdfView(){
setContentType("application/pdf");
}
@Override
protectedbooleangeneratesDownloadContent(){
returntrue;
}
@Override
protectedfinalvoidrenderMergedOutputModel(Mapmodel,HttpServletRequestrequest,
HttpServletResponseresponse)throwsException{
//获得流
ByteArrayOutputStreambaos=createTemporaryOutputStream();
Documentdocument=newDocument();
PdfWriterwriter=newWriter(document,baos);
prepareWriter(model,writer,request);
buildPdfMetadata(model,document,request);
document.open();
buildPdfDocument(model,document,writer,request,response);
document.close();
writeToResponse(response,baos);
}
protectedDocumentnewDocument(){
returnnewDocument(PageSize.A4);
}
protectedPdfWriternewWriter(Documentdocument,OutputStreamos)throwsDocumentException{
returnPdfWriter.getInstance(document,os);
}
protectedvoidprepareWriter(Mapmodel,PdfWriterwriter,HttpServletRequestrequest)
throwsDocumentException{
writer.setViewerPreferences(getViewerPreferences());
}
protectedintgetViewerPreferences(){
returnPdfWriter.ALLOW_PRINTING|PdfWriter.PageLayoutSinglePage;
}
protectedvoidbuildPdfMetadata(Mapmodel,Documentdocument,HttpServletRequestrequest){
}
protectedabstractvoidbuildPdfDocument(Mapmodel,Documentdocument,PdfWriterwriter,
HttpServletRequestrequest,HttpServletResponseresponse)throwsException;
}
pdf公共类
packagelight.mvc.utils.pdf;
importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.Map;
importcom.itextpdf.text.Chunk;
importcom.itextpdf.text.DocumentException;
importcom.itextpdf.text.Font;
importcom.itextpdf.text.Paragraph;
importcom.itextpdf.text.pdf.BaseFont;
/**
*@ClassName:PDFUtil
*@Description:
*@authorliuyajun
*@date2017年3月2日下午1:21:21
*
*/
publicclassPDFUtil{
//对参数的封装形式比如{name}
publicstaticfinalStringBEGIN="{";
publicstaticfinalStringEND="}";
//换行形式{#}
publicstaticfinalStringNEW_LINE="#";
//默认的行间距、首行距离等,自己添加
publicstaticfinalfloatDEFAULT_LEADING=20;
publicstaticfinalfloatDEFAULT_LINE_INDENT=30;
//基本字体和样式
publicstaticBaseFontbfChinese;
publicstaticFontfontChinese;
publicstaticFontUNDER_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=newFont(bfChinese,12,Font.NORMAL);
UNDER_LINE=newFont(bfChinese,14,Font.UNDERLINE);
}catch(DocumentExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
//默认样式
publicstaticParagraphgetParagraph(Stringcontext){
returngetParagraph(context,fontChinese);
}
publicstaticParagraphgetParagraph(Chunkchunk){
returnnewParagraph(chunk);
}
//指定字体样式
publicstaticParagraphgetParagraph(Stringcontext,Fontfont){
returnnewParagraph(context,font);
}
//获得新行,首行缩进,和行间距
publicstaticParagraphgetNewParagraph(Stringcontext,floatfixedLeading,floatfirstLineIndent){
Paragraphp=getParagraph(context);
p.setLeading(fixedLeading);
p.setFirstLineIndent(firstLineIndent);
returnp;
}
publicstaticParagraphgetParagraph(Stringcontent,Fontfont,floatfixedLeading,intalignment){
Paragraphp=getParagraph(content);
p.setFont(font);
p.setLeading(fixedLeading);
p.setAlignment(alignment);
returnp;
}
//默认段落样式
publicstaticParagraphgetDefaultParagraph(Stringcontext){
Paragraphp=getParagraph(context);
//默认行间距
p.setLeading(DEFAULT_LEADING);
//默认首行空隙
p.setFirstLineIndent(DEFAULT_LINE_INDENT);
returnp;
}
//将参数和字符串内容组合成集合
publicstaticListcreateParagraphs(Stringcontext,Mapmap){
intindex=0;
Listlist=newArrayList();
Paragraphp=getDefaultParagraph(null);
while((index=context.indexOf(BEGIN))>-1){
Stringtext=context.substring(0,index);
context=context.substring(index,context.length());
index=context.indexOf(END);
Stringparam=null;
if(index>0){
param=context.substring(BEGIN.length(),index);
}
p.add(text);
if(!NEW_LINE.equals(param)){
Objectvalue=map.get(param);
if(value!=null){
p.add(newChunk(value.toString(),UNDER_LINE));
}else{
p.add(newChunk(""));
}
}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));
returnlist;
}
}
生成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(Mapmodel,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);
//表格标题
Listtitles=(List)model.get("titles");
intlen=titles.size();
PdfPTabletable=newPdfPTable(len);
table.setSpacingBefore(20);
table.setSpacingAfter(30);
for(inti=0;ilogList=(List)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,ListlogList){
intlogCount=logList.size();
if(logList!=null&&logCount>0){
for(inti=0;i
调用
/**
*导出用户信息到excel/pdf
*@return
*/
@RequestMapping("/download")
publicModelAndViewexport2Excel(HttpServletRequestrequest,Loglog){
SessionInfosessionInfo=(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());
}
PageFilterph=newPageFilter();
ph.setSort("createdatetime");
ph.setOrder("desc");
Listlist=logService.dataGrid(log,ph);
MapdataMap=newHashMap();
Listtitles=newArrayList();
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");
Stringstr=request.getParameter("str");
ModelAndViewmv=null;
if("excel".equals(str)){
ExcelViewexcel=newExcelView();
mv=newModelAndView(excel,dataMap);
}elseif("pdf".equals(str)){
PdfViewpdf=newPdfView();
mv=newModelAndView(pdf,dataMap);
}
insertlog(request,"下载"+str+"文件",2);
returnmv;
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。