欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-02 17:57:16
整理文档,搜刮出一个spring 实现excel及pdf导出表格的代码,稍微整理精简一下做下分享。 excel 导出: package light.mv...

整理文档,搜刮出一个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; 
  } 

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