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

发布时间 - 2026-01-11 00:24:45    点击率:

整理文档,搜刮出一个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<String, Object> 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<String> titles = (List<String>) 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<len; i++){ //设置标题 
      String title = titles.get(i); 
      cell = getCell(sheet, 0, i); 
      cell.setCellStyle(headerStyle); 
      setText(cell,title); 
    } 
    sheet.getRow(0).setHeight(height); 
     
    HSSFCellStyle contentStyle = workbook.createCellStyle(); //内容样式 
    contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); 
    String type = (String) model.get("type"); 
    if ("log".equals(type)){ 
      List<Log> logList = (List<Log>) model.get("list"); 
      logExcel(logList, contentStyle); 
    } 
     
  } 
  /** 
   * 
  * @Title: logExcel 
  * @Description: 日志导出 
  * @param @param logList 
  * @param @param contentStyle 
  * @return void 
  * @throws 
   */ 
  public void logExcel(List<Log> logList, HSSFCellStyle contentStyle){ 
    int logCount = logList.size(); 
    if (logList != null && logCount > 0){ 
      for(int i=0; i<logCount; i++){ 
        Log log = logList.get(i); 
        String loginname = log.getLoginname(); 
        cell = getCell(sheet, i+1, 0); 
        cell.setCellStyle(contentStyle); 
        setText(cell,loginname); 
         
        String username = log.getName(); 
        cell = getCell(sheet, i+1, 1); 
        cell.setCellStyle(contentStyle); 
        setText(cell,username); 
         
        String IP = log.getIp(); 
        cell = getCell(sheet, i+1, 2); 
        cell.setCellStyle(contentStyle); 
        setText(cell,IP); 
         
        String organizationName = log.getOrganizationName(); 
        cell = getCell(sheet, i+1, 3); 
        cell.setCellStyle(contentStyle); 
        setText(cell,organizationName); 
         
        String usertype = log.getUsertype()==0 ? "管理员" : "员工"; 
        cell = getCell(sheet, i+1, 4); 
        cell.setCellStyle(contentStyle); 
        setText(cell,usertype); 
         
        String msg = log.getMsg(); 
        cell = getCell(sheet, i+1, 5); 
        cell.setCellStyle(contentStyle); 
        setText(cell,msg); 
         
        Date lastLogin = log.getCreatedatetime()!=null ? log.getCreatedatetime() : null; 
        cell = getCell(sheet, i+1, 6); 
        cell.setCellStyle(contentStyle); 
        setText(cell,Tools.date2Str(lastLogin)); 
      } 
    } 
  } 
} 

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; 
 
/** 
 * 这里就全部复制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 公共类

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

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; 
 
/** 
* @ClassName: LogPdfView 
* @Description: 
* @author liuyajun 
* @date 2017年3月2日 上午11:18:44 
* 
*/ 
public class PdfView extends AbstractIText5PdfView{ 
 
  @Override 
  protected void buildPdfDocument(Map<String, Object> 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<String> titles = (List<String>) model.get("titles"); 
      int len = titles.size(); 
      PdfPTable table = new PdfPTable(len);  
      table.setSpacingBefore(20);  
      table.setSpacingAfter(30);  
      for(int i=0; i<len; i++){ //设置标题 
        String str = titles.get(i); 
        table.addCell(PDFUtil.getParagraph(str));  
      } 
       
      // 表格数据  
      String type = (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 (Exception e) {  
      e.printStackTrace();  
    }  
     
  } 
   
  /** 
   * 
  * @Title: logPdf 
  * @Description: 日志导出 
  * @param @param table 
  * @param @param logList 
  * @param @return 
  * @return PdfPTable 
  * @throws 
   */ 
  public PdfPTable logPdf(PdfPTable table, List<Log> logList){ 
    int logCount = logList.size(); 
    if (logList != null && logCount > 0){ 
      for(int i=0; i<logCount; i++){ 
        Log log = logList.get(i); 
        String loginname = log.getLoginname(); 
        table.addCell(PDFUtil.getParagraph(loginname));  
         
        String username = log.getName(); 
        table.addCell(PDFUtil.getParagraph(username)); 
         
        String IP = log.getIp(); 
        table.addCell(PDFUtil.getParagraph(IP)); 
         
        String organizationName = log.getOrganizationName(); 
        table.addCell(PDFUtil.getParagraph(organizationName)); 
         
        String usertype = log.getUsertype()==0 ? "管理员" : "员工"; 
        table.addCell(PDFUtil.getParagraph(usertype)); 
         
        String msg = log.getMsg(); 
        table.addCell(PDFUtil.getParagraph(msg)); 
         
        Date lastLogin = log.getCreatedatetime()!=null ? log.getCreatedatetime() : null; 
        table.addCell(PDFUtil.getParagraph(Tools.date2Str(lastLogin))); 
      } 
    } 
    return table; 
     
  } 
 
} 

调用

/** 
   * 导出用户信息到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; 
  } 

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


# spring  # excel  # 导出  # 导出pdf  # springmvc导出pdf  # Springboot使用POI实现导出Excel文件示例  # Spring Boot Excel文件导出下载实现代码  # Springboot上传excel并将表格数据导入或更新mySql数据库的过程  # 使用Vue+Spring Boot实现Excel上传功能  # springboot实现上传并解析Excel过程解析  # SpringBoot使用POI进行Excel下载  # java springboot poi 从controller 接收不同类型excel 文件处理  # SpringMVC上传和解析Excel方法  # 详解poi+springmvc+springjdbc导入导出excel实例  # spring boot读取Excel操作示例  # 行间  # 的是  # 重写  # 第三方  # 登录名  # 大家多多  # 换行  # 上午  # 下午  # 就行了  # 行空  # 文档  # headerFont  # VERTICAL_CENTER  # setBoldweight  # createFont  # setAlignment  # createCellStyle  # setVerticalAlignment  # ALIGN_CENTER 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: Android利用动画实现背景逐渐变暗  如何确保FTP站点访问权限与数据传输安全?  Laravel如何实现本地化和多语言支持_Laravel多语言配置与翻译文件管理  制作旅游网站html,怎样注册旅游网站?  敲碗10年!Mac系列传将迎来「触控与联网」双革新  非常酷的网站设计制作软件,酷培ai教育官方网站?  免费视频制作网站,更新又快又好的免费电影网站?  高防服务器租用首荐平台,企业级优惠套餐快速部署  如何基于云服务器快速搭建个人网站?  Win11怎样安装网易有道词典_Win11安装词典教程【步骤】  Edge浏览器怎么启用睡眠标签页_节省电脑内存占用优化技巧  香港服务器租用每月最低只需15元?  laravel怎么在请求结束后执行任务(Terminable Middleware)_laravel Terminable Middleware请求结束任务执行方法  Laravel如何从数据库删除数据_Laravel destroy和delete方法区别  微信小程序 scroll-view组件实现列表页实例代码  怎样使用JSON进行数据交换_它有什么限制  JS中使用new Date(str)创建时间对象不兼容firefox和ie的解决方法(两种)  如何在 Python 中将列表项按字母顺序编号(a.、b.、c. …)  详解ASP.NET 生成二维码实例(采用ThoughtWorks.QRCode和QrCode.Net两种方式)  Java垃圾回收器的方法和原理总结  如何登录建站主机?访问步骤全解析  Laravel如何配置中间件Middleware_Laravel自定义中间件拦截请求与权限校验【步骤】  香港服务器选型指南:免备案配置与高效建站方案解析  千问怎样用提示词获取健康建议_千问健康类提示词注意事项【指南】  Laravel怎么在Controller之外的地方验证数据  Linux系统运维自动化项目教程_Ansible批量管理实战  Laravel Sail是什么_基于Docker的Laravel本地开发环境Sail入门  深圳网站制作公司好吗,在深圳找工作哪个网站最好啊?  如何快速搭建FTP站点实现文件共享?  Laravel怎么实现一对多关联查询_Laravel Eloquent模型关系定义与预加载【实战】  微信公众帐号开发教程之图文消息全攻略  微信小程序 配置文件详细介绍  Laravel怎么进行数据库事务处理_Laravel DB Facade事务操作确保数据一致性  如何撰写建站申请书?关键要点有哪些?  Laravel怎么在Blade中安全地输出原始HTML内容  Laravel怎么返回JSON格式数据_Laravel API资源Response响应格式化【技巧】  canvas 画布在主流浏览器中的尺寸限制详细介绍  Windows10电脑怎么查看硬盘通电时间_Win10使用工具检测磁盘健康  如何在宝塔面板中修改默认建站目录?  Laravel如何配置和使用缓存?(Redis代码示例)  javascript和jQuery中的AJAX技术详解【包含AJAX各种跨域技术】  JS中对数组元素进行增删改移的方法总结  教你用AI润色文章,让你的文字表达更专业  Win11怎么关闭资讯和兴趣_Windows11任务栏设置隐藏小组件  大型企业网站制作流程,做网站需要注册公司吗?  如何在建站之星绑定自定义域名?  如何快速完成中国万网建站详细流程?  Laravel Fortify是什么,和Jetstream有什么关系  Python文件流缓冲机制_IO性能解析【教程】  jquery插件bootstrapValidator表单验证详解