最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于SpringBoot框架管理Excel和PDF文件類型

 更新時(shí)間:2020年02月07日 10:05:50   作者:知了一笑  
這篇文章主要介紹了基于SpringBoot框架,管理Excel和PDF文件類型,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

一、文檔類型簡(jiǎn)介

1、Excel文檔

Excel一款電子表格軟件。直觀的界面、出色的計(jì)算功能和圖表工具,在系統(tǒng)開發(fā)中,經(jīng)常用來把數(shù)據(jù)轉(zhuǎn)存到Excel文件,或者Excel數(shù)據(jù)導(dǎo)入系統(tǒng)中,這就涉及數(shù)據(jù)轉(zhuǎn)換問題。

2、PDF文檔

PDF是可移植文檔格式,是一種電子文件格式,具有許多其他電子文檔格式無法相比的優(yōu)點(diǎn)。PDF文件格式可以將文字、字型、格式、顏色及獨(dú)立于設(shè)備和分辨率的圖形圖像等封裝在一個(gè)文件中。該格式文件還可以包含超文本鏈接、聲音和動(dòng)態(tài)影像等電子信息,支持特長文件,集成度和安全可靠性都較高。

二、Excel文件管理

1、POI依賴

Apache POI是Apache軟件基金會(huì)的開源類庫,POI提供API給Java程序?qū)icrosoft Office格式檔案讀和寫的功能。

<!-- Excel 依賴 -->
<dependency>
 <groupId>org.apache.poi</groupId>
 <artifactId>poi</artifactId>
 <version>3.9</version>
</dependency>
<!-- 2007及更高版本 -->
<dependency>
 <groupId>org.apache.poi</groupId>
 <artifactId>poi-ooxml</artifactId>
 <version>3.9</version>
</dependency>

2、文件讀取

public static List<List<Object>> readExcel(String path) throws Exception {
 File file = new File(path) ;
 List<List<Object>> list = new LinkedList<>();
 XSSFWorkbook xwb = new XSSFWorkbook(new FileInputStream(file));
 // 讀取 Sheet1 表格內(nèi)容
 XSSFSheet sheet = xwb.getSheetAt(0);
 // 讀取行數(shù):不讀取Excel表頭
 for (int i = (sheet.getFirstRowNum()+1); i <= (sheet.getPhysicalNumberOfRows()-1); i++) {
  XSSFRow row = sheet.getRow(i);
  if (row == null) { continue; }
  List<Object> linked = new LinkedList<>();
  for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
   XSSFCell cell = row.getCell(j);
   if (cell == null) { continue; }
   Object value ;
   // 這里需根據(jù)實(shí)際業(yè)務(wù)情況處理
   switch (cell.getCellType()) {
    case XSSFCell.CELL_TYPE_NUMERIC:
     //處理數(shù)值帶{.0}問題
     value = Double.valueOf(String.valueOf(cell)).longValue() ;
     break;
    default:
     value = cell.toString();
   }
   linked.add(value);
  }
  if (linked.size()!= 0) {
   list.add(linked);
  }
 }
 return list;
}

3、文件創(chuàng)建

public static void createExcel(String excelName, String[] headList,List<List<Object>> dataList)
  throws Exception {
 // 創(chuàng)建 Excel 工作簿
 XSSFWorkbook workbook = new XSSFWorkbook();
 XSSFSheet sheet = workbook.createSheet();
 // 創(chuàng)建表頭
 XSSFRow row = sheet.createRow(0);
 for (int i = 0; i < headList.length; i++) {
  XSSFCell cell = row.createCell(i);
  cell.setCellType(XSSFCell.CELL_TYPE_STRING);
  cell.setCellValue(headList[i]);
 }
 //添加數(shù)據(jù)
 for (int line = 0; line < dataList.size(); line++) {
  XSSFRow rowData = sheet.createRow(line+1);
  List<Object> data = dataList.get(line);
  for (int j = 0; j < headList.length; j++) {
   XSSFCell cell = rowData.createCell(j);
   cell.setCellType(XSSFCell.CELL_TYPE_STRING);
   cell.setCellValue((data.get(j)).toString());
  }
 }
 FileOutputStream fos = new FileOutputStream(excelName);
 workbook.write(fos);
 fos.flush();
 fos.close();
}

4、文件導(dǎo)出

public static void exportExcel(String[] headList, List<List<Object>> dataList,
        OutputStream outputStream) throws Exception {
 // 創(chuàng)建 Excel 工作簿
 XSSFWorkbook workbook = new XSSFWorkbook();
 XSSFSheet sheet = workbook.createSheet();
 // 創(chuàng)建表頭
 XSSFRow row = sheet.createRow(0);
 for (int i = 0; i < headList.length; i++) {
  XSSFCell cell = row.createCell(i);
  cell.setCellType(XSSFCell.CELL_TYPE_STRING);
  cell.setCellValue(headList[i]);
 }
 //添加數(shù)據(jù)
 for (int line = 0; line < dataList.size(); line++) {
  XSSFRow rowData = sheet.createRow(line+1);
  List<Object> data = dataList.get(line);
  for (int j = 0; j < headList.length; j++) {
   XSSFCell cell = rowData.createCell(j);
   cell.setCellType(XSSFCell.CELL_TYPE_STRING);
   cell.setCellValue((data.get(j)).toString());
  }
 }
 workbook.write(outputStream);
 outputStream.flush();
 outputStream.close();
}

5、文件導(dǎo)出接口

@RestController
public class ExcelWeb {
 @RequestMapping("/web/outExcel")
 public void outExcel (HttpServletResponse response) throws Exception {
  String exportName = "2020-01-user-data" ;
  response.setContentType("application/vnd.ms-excel");
  response.addHeader("Content-Disposition", "attachment;filename="+
        URLEncoder.encode(exportName, "UTF-8") + ".xlsx");
  List<List<Object>> dataList = ExcelUtil.readExcel("F:\\file-type\\user-excel.xlsx") ;
  String[] headList = new String[]{"用戶ID", "用戶名", "手機(jī)號(hào)"} ;
  ExcelUtil.exportExcel(headList,dataList,response.getOutputStream()) ;
 }
}

三、PDF文件管理

1、IText依賴

iText是一種生成PDF報(bào)表的Java組件。通過在服務(wù)器端使用頁面或API封裝生成PDF報(bào)表,客戶端可以通過超鏈接直接顯示或下載到本地,在系統(tǒng)開發(fā)中通常用來生成比較正式的報(bào)告或者合同類的電子文檔。

<dependency>
 <groupId>com.itextpdf</groupId>
 <artifactId>itextpdf</artifactId>
 <version>5.5.11</version>
</dependency>
<dependency>
 <groupId>com.itextpdf.tool</groupId>
 <artifactId>xmlworker</artifactId>
 <version>5.5.11</version>
</dependency>

2、API二次封裝

首先對(duì)于Itext提供的API做一下表格、段落、圖片等基礎(chǔ)樣式的二次封裝,可以更好的適配業(yè)務(wù)。

public class PdfFontUtil {
 private PdfFontUtil(){}

 /**
  * 段落樣式獲取
  */
 public static Paragraph getParagraph (String content, Font font,Integer alignment){
  Paragraph paragraph = new Paragraph(content,font) ;
  if (alignment != null && alignment >= 0){
   paragraph.setAlignment(alignment);
  }
  return paragraph ;
 }
 /**
  * 圖片樣式
  */
 public static Image getImage (String imgPath,float width,float height) throws Exception {
  Image image = Image.getInstance(imgPath);
  image.setAlignment(Image.MIDDLE);
  if (width > 0 && height > 0){
   image.scaleAbsolute(width, height);
  }
  return image ;
 }
 /**
  * 表格生成
  */
 public static PdfPTable getPdfPTable01 (int numColumns,float totalWidth) throws Exception {
  // 表格處理
  PdfPTable table = new PdfPTable(numColumns);
  // 設(shè)置表格寬度比例為%100
  table.setWidthPercentage(100);
  // 設(shè)置寬度:寬度平均
  table.setTotalWidth(totalWidth);
  // 鎖住寬度
  table.setLockedWidth(true);
  // 設(shè)置表格上面空白寬度
  table.setSpacingBefore(10f);
  // 設(shè)置表格下面空白寬度
  table.setSpacingAfter(10f);
  // 設(shè)置表格默認(rèn)為無邊框
  table.getDefaultCell().setBorder(0);
  table.setPaddingTop(50);
  table.setSplitLate(false);
  return table ;
 }
 /**
  * 表格內(nèi)容
  */
 public static PdfPCell getPdfPCell (Phrase phrase){
  return new PdfPCell (phrase) ;
 }
 /**
  * 表格內(nèi)容帶樣式
  */
 public static void addTableCell (PdfPTable dataTable,Font font,List<String> cellList){
  for (String content:cellList) {
   dataTable.addCell(getParagraph(content,font,-1));
  }
 }
}

3、生成PDF文件

這里基于上面的工具類,畫一個(gè)PDF頁面作為參考。

public class PdfPage01 {
 // 基礎(chǔ)配置
 private static String PDF_SITE = "F:\\file-type\\PDF頁面2020-01-15.pdf" ;
 private static String FONT = "C:/Windows/Fonts/simhei.ttf";
 private static String PAGE_TITLE = "PDF數(shù)據(jù)導(dǎo)出報(bào)告" ;
 // 基礎(chǔ)樣式
 private static Font TITLE_FONT = FontFactory.getFont(FONT, BaseFont.IDENTITY_H,20, Font.BOLD);
 private static Font NODE_FONT = FontFactory.getFont(FONT, BaseFont.IDENTITY_H,15, Font.BOLD);
 private static Font BLOCK_FONT = FontFactory.getFont(FONT, BaseFont.IDENTITY_H,13, Font.BOLD, BaseColor.BLACK);
 private static Font INFO_FONT = FontFactory.getFont(FONT, BaseFont.IDENTITY_H,12, Font.NORMAL,BaseColor.BLACK);
 private static Font CONTENT_FONT = FontFactory.getFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

 private static void createPdfPage () throws Exception {
  // 創(chuàng)建文檔
  Document document = new Document();
  PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(PDF_SITE));
  document.open();
  // 報(bào)告標(biāo)題
  document.add(PdfFontUtil.getParagraph(PAGE_TITLE,TITLE_FONT,1)) ;
  document.add(PdfFontUtil.getParagraph("\n商戶名稱:XXX科技有限公司",INFO_FONT,-1)) ;
  document.add(PdfFontUtil.getParagraph("\n生成時(shí)間:2020-01-15\n\n",INFO_FONT,-1)) ;
  // 報(bào)告內(nèi)容
  // 段落標(biāo)題 + 報(bào)表圖
  document.add(PdfFontUtil.getParagraph("城市數(shù)據(jù)分布統(tǒng)計(jì)",NODE_FONT,-1)) ;
  document.add(PdfFontUtil.getParagraph("\n· 可視化圖表\n\n",BLOCK_FONT,-1)) ;
  // 設(shè)置圖片寬高
  float documentWidth = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin();
  float documentHeight = documentWidth / 580 * 320;
  document.add(PdfFontUtil.getImage("F:\\file-type\\myChart.jpg",documentWidth-80,documentHeight-80)) ;
  // 數(shù)據(jù)表格
  document.add(PdfFontUtil.getParagraph("\n· 數(shù)據(jù)詳情\n\n",BLOCK_FONT,-1)) ;
  PdfPTable dataTable = PdfFontUtil.getPdfPTable01(4,400) ;
  // 設(shè)置表格
  List<String> tableHeadList = tableHead () ;
  List<List<String>> tableDataList = getTableData () ;
  PdfFontUtil.addTableCell(dataTable,CONTENT_FONT,tableHeadList);
  for (List<String> tableData : tableDataList) {
   PdfFontUtil.addTableCell(dataTable,CONTENT_FONT,tableData);
  }
  document.add(dataTable);
  document.add(PdfFontUtil.getParagraph("\n· 報(bào)表描述\n\n",BLOCK_FONT,-1)) ;
  document.add(PdfFontUtil.getParagraph("數(shù)據(jù)報(bào)告可以監(jiān)控每天的推廣情況," +
    "可以針對(duì)不同的數(shù)據(jù)表現(xiàn)進(jìn)行分析,以提升推廣效果。",CONTENT_FONT,-1)) ;
  document.newPage() ;
  document.close();
  writer.close();
 }
 private static List<List<String>> getTableData (){
  List<List<String>> tableDataList = new ArrayList<>() ;
  for (int i = 0 ; i < 3 ; i++){
   List<String> tableData = new ArrayList<>() ;
   tableData.add("浙江"+i) ;
   tableData.add("杭州"+i) ;
   tableData.add("276"+i) ;
   tableData.add("33.3%") ;
   tableDataList.add(tableData) ;
  }
  return tableDataList ;
 }
 private static List<String> tableHead (){
  List<String> tableHeadList = new ArrayList<>() ;
  tableHeadList.add("省份") ;
  tableHeadList.add("城市") ;
  tableHeadList.add("數(shù)量") ;
  tableHeadList.add("百分比") ;
  return tableHeadList ;
 }
 public static void main(String[] args) throws Exception {
  createPdfPage () ;
 }
}

4、頁面效果

四、網(wǎng)頁轉(zhuǎn)PDF

1、頁面Jar包依賴

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2、編寫頁面樣式

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
 <meta charset="UTF-8"/>
 <title>Title</title>
 <style>
  body{font-family:SimSun;}
 </style>
</head>
<body>
項(xiàng)目信息:<br/>
名稱:${name}<br/>
作者:${author}<br/><br/>
<img 
src="https://img2018.cnblogs.com/blog/1691717/201906/1691717-20190603213911854-1098366582.jpg"/>
<br/>
</body>
</html>

3、核心配置類

public class PageConfig {
 private static final String DEST = "F:\\file-type\\HTML頁面2020-01-15.pdf";
 private static final String HTML = "/pdf_page_one.html";
 private static final String FONT = "C:/Windows/Fonts/simsun.ttc";
 private static Configuration freemarkerCfg = null ;
 static {
  freemarkerCfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
  //freemarker的模板目錄
  try {
   String path = "TODO:模板路徑{自定義}" ;
   freemarkerCfg.setDirectoryForTemplateLoading(new File(path));
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 /**
  * 創(chuàng)建文檔
  */
 private static void createPdf(String content,String dest) throws Exception {
  Document document = new Document();
  PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
  document.open();
  XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
  fontImp.register(FONT);
  XMLWorkerHelper.getInstance().parseXHtml(writer, document,
    new ByteArrayInputStream(content.getBytes()), null, Charset.forName("UTF-8"), fontImp);
  document.close();
 }
 /**
  * 頁面渲染
  */
 private static String freeMarkerRender(Map<String, Object> data, String htmlTmp) throws Exception {
  Writer out = new StringWriter();
  Template template = freemarkerCfg.getTemplate(htmlTmp,"UTF-8");
  template.process(data, out);
  out.flush();
  out.close();
  return out.toString();
 }
 /**
  * 方法入口
  */
 public static void main(String[] args) throws Exception {
  Map<String,Object> data = new HashMap<> ();
  data.put("name","smile");
  data.put("author","知了") ;
  String content = PageConfig.freeMarkerRender(data,HTML);
  PageConfig.createPdf(content,DEST);
 }
}

4、轉(zhuǎn)換效果圖

五、源代碼地址

文中涉及文件類型,在該章節(jié)源碼ware18-file-parent/case-file-type目錄下。

GitHub·地址
https://github.com/cicadasmile/middle-ware-parent
GitEE·地址
https://gitee.com/cicadasmile/middle-ware-parent

總結(jié)

以上所述是小編給大家介紹的基于SpringBoot框架管理Excel和PDF文件類型,希望對(duì)大家有所幫助!

相關(guān)文章

  • 使用springboot配置和占位符獲取配置文件中的值

    使用springboot配置和占位符獲取配置文件中的值

    這篇文章主要介紹了使用springboot配置和占位符獲取配置文件中的值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • IDEA 將 SpringBoot 項(xiàng)目打包成jar的方法

    IDEA 將 SpringBoot 項(xiàng)目打包成jar的方法

    這篇文章主要介紹了IDEA 將 SpringBoot 項(xiàng)目打包成jar的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-09-09
  • ssm?mybatis如何配置多個(gè)mapper目錄

    ssm?mybatis如何配置多個(gè)mapper目錄

    這篇文章主要介紹了ssm?mybatis如何配置多個(gè)mapper目錄,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
    2022-01-01
  • 關(guān)于Java中@SuppressWarnings的正確使用方法

    關(guān)于Java中@SuppressWarnings的正確使用方法

    這篇文章主要介紹了關(guān)于Java中@SuppressWarnings的正確使用方法,@SuppressWarnings注解主要用在取消一些編譯器產(chǎn)生的警告對(duì)代碼左側(cè)行列的遮擋,有時(shí)候這會(huì)擋住我們斷點(diǎn)調(diào)試時(shí)打的斷點(diǎn),需要的朋友可以參考下
    2023-05-05
  • SpringBoot2 Jpa 批量刪除功能的實(shí)現(xiàn)

    SpringBoot2 Jpa 批量刪除功能的實(shí)現(xiàn)

    這篇文章主要介紹了SpringBoot2 Jpa 批量刪除功能的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2021-01-01
  • SpringBoot實(shí)現(xiàn)Thymeleaf驗(yàn)證碼生成

    SpringBoot實(shí)現(xiàn)Thymeleaf驗(yàn)證碼生成

    本文使用SpringBoot實(shí)現(xiàn)Thymeleaf驗(yàn)證碼生成,使用后臺(tái)返回驗(yàn)證碼圖片,驗(yàn)證碼存到session中后端實(shí)現(xiàn)校驗(yàn),前端只展示驗(yàn)證碼圖片。感興趣的可以了解下
    2021-05-05
  • 詳解堆排序算法原理及Java版的代碼實(shí)現(xiàn)

    詳解堆排序算法原理及Java版的代碼實(shí)現(xiàn)

    如果將堆理解為二叉樹,那么樹中任一非葉結(jié)點(diǎn)的關(guān)鍵字均不大于(或不小于)其左右孩子(若存在)結(jié)點(diǎn)的關(guān)鍵字,堆排序的時(shí)間復(fù)雜度為O(N*logN),這里我們就來詳解堆排序算法原理及Java版的代碼實(shí)現(xiàn)
    2016-06-06
  • java DataInputStream和DataOutputStream詳解及實(shí)例代碼

    java DataInputStream和DataOutputStream詳解及實(shí)例代碼

    這篇文章主要介紹了java DataInputStream和DataOutputStream詳解及實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下
    2017-01-01
  • Java設(shè)計(jì)模式之單例模式深入探索

    Java設(shè)計(jì)模式之單例模式深入探索

    單例模式(Singleton Pattern)是 Java 中最簡(jiǎn)單的設(shè)計(jì)模式之一。這種類型的設(shè)計(jì)模式屬于創(chuàng)建型模式,它提供了一種創(chuàng)建對(duì)象的最佳方式,這種模式涉及到一個(gè)單一的類,該類負(fù)責(zé)創(chuàng)建自己的對(duì)象,同時(shí)確保只有單個(gè)對(duì)象被創(chuàng)建
    2021-10-10
  • 單臺(tái)Spring Cloud Eureka升級(jí)到三臺(tái)Eureka高可用集群

    單臺(tái)Spring Cloud Eureka升級(jí)到三臺(tái)Eureka高可用集群

    今天小編就為大家分享一篇關(guān)于單臺(tái)Spring Cloud Eureka升級(jí)到三臺(tái)Eureka高可用集群,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2018-12-12

最新評(píng)論

桂平市| 西城区| 和田县| 延寿县| 宁国市| 桂东县| 永寿县| 清水县| 衢州市| 西平县| 成武县| 沅江市| 林周县| 合水县| 石柱| 廊坊市| 宝坻区| 永川市| 洛南县| 印江| 丰顺县| 龙川县| 伊金霍洛旗| 海口市| 台山市| 彭泽县| 沁阳市| 湘乡市| 仙游县| 梅州市| 新和县| 仁怀市| 德令哈市| 墨竹工卡县| 肥西县| 泾阳县| 厦门市| 龙门县| 阿克陶县| 大庆市| 三门峡市|