亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Spring 實現(xiàn)excel及pdf導出表格示例

 更新時間:2017年03月28日 16:50:10   作者:DFDHZ  
本篇文章主要介紹了Spring 實現(xiàn)excel及pdf導出表格示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

整理文檔,搜刮出一個Spring 實現(xiàn)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(); //內(nèi)容樣式 
    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調(diào)用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 { 
  // 對參數(shù)的封裝形式比如{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 默認系統(tǒng)語言,這里沒使用第三方語言包 
      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; 
  } 
   
  // 將參數(shù)和字符串內(nèi)容組合成集合 
  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));  
      } 
       
      // 表格數(shù)據(jù)  
      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; 
     
  } 
 
} 

調(diào)用

/** 
   * 導出用戶信息到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("操作內(nèi)容"); 
    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; 
  } 

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • RestTemplate發(fā)送HTTP?GET請求使用方法詳解

    RestTemplate發(fā)送HTTP?GET請求使用方法詳解

    這篇文章主要為大家介紹了關于RestTemplate發(fā)送HTTP?GET請求的使用方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家<BR>33+多多進步
    2022-03-03
  • java springboot poi 從controller 接收不同類型excel 文件處理

    java springboot poi 從controller 接收不同類型excel 文件處理

    這篇文章主要介紹了java springboot poi 從controller 接收不同類型excel 文件處理,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-10-10
  • java 數(shù)據(jù)的加密與解密普遍實例代碼

    java 數(shù)據(jù)的加密與解密普遍實例代碼

    本篇文章介紹了一個關于密鑰查詢的jsp文件簡單實例代碼,需要的朋友可以參考下
    2017-04-04
  • JAVA中反射機制和模塊化的深入講解

    JAVA中反射機制和模塊化的深入講解

    很多剛學Java反射的同學可能對反射技術(shù)一頭霧水,為什么要學習反射,學習反射有什么作用,下面這篇文章主要給大家介紹了關于JAVA中反射機制和模塊化的相關資料,需要的朋友可以參考下
    2021-09-09
  • 一步步教你搭建Scala開發(fā)環(huán)境(非常詳細!)

    一步步教你搭建Scala開發(fā)環(huán)境(非常詳細!)

    Scala是一門基于jvm的函數(shù)式的面向?qū)ο缶幊陶Z言,擁有比java更加簡潔的語法,下面這篇文章主要給大家介紹了關于搭建Scala開發(fā)環(huán)境的相關資料,文中通過圖文介紹的非常詳細,需要的朋友可以參考下
    2022-04-04
  • SpringCloud實戰(zhàn)小貼士之Zuul的路徑匹配

    SpringCloud實戰(zhàn)小貼士之Zuul的路徑匹配

    這篇文章主要介紹了SpringCloud實戰(zhàn)小貼士之Zuul的路徑匹配,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-10-10
  • Apache Calcite進行SQL解析(java代碼實例)

    Apache Calcite進行SQL解析(java代碼實例)

    Calcite是一款開源SQL解析工具, 可以將各種SQL語句解析成抽象語法樹AST(Abstract Syntax Tree), 之后通過操作AST就可以把SQL中所要表達的算法與關系體現(xiàn)在具體代碼之中,今天通過代碼實例給大家介紹Apache Calcite進行SQL解析問題,感興趣的朋友一起看看吧
    2022-01-01
  • MybatisPlus出現(xiàn)Error attempting to get column ‘xxx字段‘ from result set異常解決

    MybatisPlus出現(xiàn)Error attempting to get col

    本文重點分析使用@EnumValue注解轉(zhuǎn)換時遇到的一下錯誤原因,及解決方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-11-11
  • Java線程的并發(fā)工具類實現(xiàn)原理解析

    Java線程的并發(fā)工具類實現(xiàn)原理解析

    本文給大家講解Java線程的并發(fā)工具類的一些知識,通過適用場景分析大數(shù)據(jù)量統(tǒng)計類任務的實現(xiàn)原理和封裝,多個示例代碼講解的非常詳細,對java線程并發(fā)工具類相關知識感興趣的朋友一起學習下吧
    2021-06-06
  • java連連看游戲菜單設計

    java連連看游戲菜單設計

    這篇文章主要為大家詳細介紹了java連連看游戲菜單部分的設計代碼,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-12-12

最新評論