栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

excel 导出:

package light.mvc.utils.excel; 
 
import java.util.Date; 
import java.util.List; 
import java.util.Map; 
 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
import org.apache.poi.hssf.usermodel.HSSFCell; 
import org.apache.poi.hssf.usermodel.HSSFCellStyle; 
import org.apache.poi.hssf.usermodel.HSSFFont; 
import org.apache.poi.hssf.usermodel.HSSFSheet; 
import org.apache.poi.hssf.usermodel.HSSFWorkbook; 
import org.springframework.web.servlet.view.document.AbstractExcelView; 
 
import light.mvc.pageModel.sys.Log; 
import light.mvc.utils.Tools; 
 
 
public class ExcelView extends AbstractExcelView{ 
   
  private HSSFSheet sheet; 
  private HSSFCell cell; 
 
  @Override 
  protected void buildExceldocument(Map model, 
      HSSFWorkbook workbook, HttpServletRequest request, 
      HttpServletResponse response) throws Exception { 
    // TODO Auto-generated method stub 
    Date date = new Date(); 
    String filename = Tools.date2Str(date, "yyyyMMddHHmmss"); 
    String title_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 titles = (List) model.get("titles"); 
    int len = titles.size(); 
    HSSFCellStyle headerStyle = workbook.createCellStyle(); //标题样式 
    headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); 
    headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); 
    HSSFFont headerFont = workbook.createFont();  //标题字体 
    headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); 
    headerFont.setFontHeightInPoints((short)11); 
    headerStyle.setFont(headerFont); 
    short width = 20,height=25*20; 
    sheet.setDefaultColumnWidth(width); 
    for(int i=0; i logList = (List) model.get("list"); 
      logExcel(logList, contentStyle); 
    } 
     
  } 
   
  public void logExcel(List logList, HSSFCellStyle contentStyle){ 
    int logCount = logList.size(); 
    if (logList != null && logCount > 0){ 
      for(int i=0; i

pdf导出:

重写spring调用itext

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; 
 
 
public abstract class AbstractIText5PdfView extends AbstractView { 
  public AbstractIText5PdfView() { 
    setContentType("application/pdf"); 
  } 
 
  @Override 
  protected boolean generatesDownloadContent() { 
    return true; 
  } 
 
  @Override 
  protected final void renderMergedOutputModel(Map 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 model, PdfWriter writer, HttpServletRequest request) 
      throws documentException { 
 
    writer.setViewerPreferences(getViewerPreferences()); 
  } 
 
  protected int getViewerPreferences() { 
    return PdfWriter.ALLOW_PRINTING | PdfWriter.PageLayoutSinglePage; 
  } 
 
  protected void buildPdfmetadata(Map model, document document, HttpServletRequest request) { 
  } 
 
  protected abstract void buildPdfdocument(Map model, document document, PdfWriter writer, 
      HttpServletRequest request, HttpServletResponse response) throws Exception; 
} 

pdf 公共类

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; 
 
 
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 createParagraphs(String context ,Map map){ 
    int index = 0; 
    List list = new ArrayList(); 
    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

package light.mvc.utils.pdf; 
 
import java.util.Date; 
import java.util.List; 
import java.util.Map; 
 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
import com.itextpdf.text.Chunk; 
import com.itextpdf.text.document; 
import com.itextpdf.text.Font; 
import com.itextpdf.text.Paragraph; 
import com.itextpdf.text.pdf.PdfPTable; 
import com.itextpdf.text.pdf.PdfWriter; 
 
import light.mvc.pageModel.sys.Log; 
import light.mvc.utils.Tools; 
 
 
public class PdfView extends AbstractIText5PdfView{ 
 
  @Override 
  protected void buildPdfdocument(Map model, document document, PdfWriter writer, 
      HttpServletRequest request, HttpServletResponse response) throws Exception { 
    try{  
      document.open();  
      // 标题居中  
      String title_content = (String) model.get("title_content"); 
      Paragraph title = PDFUtil.getParagraph(  
     new Chunk(title_content,new Font(PDFUtil.bfChinese,16,Font.BOLD)));  
      title.setAlignment(Paragraph.ALIGN_CENTER);  
      document.add(title);  
 
      // 表格标题  
      List titles = (List) model.get("titles"); 
      int len = titles.size(); 
      PdfPTable table = new PdfPTable(len);  
      table.setSpacingBefore(20);  
      table.setSpacingAfter(30);  
      for(int i=0; i logList = (List) model.get("list");  
 table = logPdf(table, logList); 
      } 

      document.add(table);  
      // 关闭  
      document.close();  
    }catch (Exception e) {  
      e.printStackTrace();  
    }  
     
  } 
   
   
  public PdfPTable logPdf(PdfPTable table, List logList){ 
    int logCount = logList.size(); 
    if (logList != null && logCount > 0){ 
      for(int i=0; i

调用

 
  @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 list = logService.dataGrid(log, ph); 
    Map dataMap = new HashMap(); 
    List titles = new ArrayList(); 
    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; 
  } 

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/147070.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号