SpringBoot框架如何操作Excel和PDF

目录一、文档类型简介1、Excel文档2、PDF文档二、Excel文件管理1、POI依赖2、文件读取3、文件创建4、文件导出5、文件导出接口三、PDF文件管理1、IText依赖2、API二次封装3、生成PDF文件4、页面效果四、网页转PDF1、页面Jar包依赖2、编写页面样式3、核心配置类4、转换效果图五、源代码地址

一、文档类型简介

1、Excel文档

Excel一款电子表格软件。直观的界面、出色的计算功能和图表工具,在系统开发中,经常用来把数据转存到Excel文件,或者Excel数据导入系统中,这就涉及数据转换问题。

2、PDF文档

PDF是可移植文档格式,是一种电子文件格式,具有许多其他电子文档格式无法相比的优点。PDF文件格式可以将文字、字型、格式、颜色及独立于设备和分辨率的图形图像等封装在一个文件中。该格式文件还可以包含超文本链接、声音和动态影像等电子信息,支持特长文件,集成度和安全可靠性都较高。

二、Excel文件管理

1、POI依赖

Apache POI是Apache软件基金会的开源类库,POI提供API给Java程序对Microsoft 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、文件读取

publicstaticList<List<Object>>readExcel(Stringpath)throwsException{Filefile=newFile(path);List<List<Object>>list=newLinkedList<>();XSSFWorkbookxwb=newXSSFWorkbook(newFileInputStream(file));//读取Sheet1表格内容XSSFSheetsheet=xwb.getSheetAt(0);//读取行数:不读取Excel表头for(inti=(sheet.getFirstRowNum()+1);i<=(sheet.getPhysicalNumberOfRows()-1);i++){XSSFRowrow=sheet.getRow(i);if(row==null){continue;}List<Object>linked=newLinkedList<>();for(intj=row.getFirstCellNum();j<=row.getLastCellNum();j++){XSSFCellcell=row.getCell(j);if(cell==null){continue;}Objectvalue;//这里需根据实际业务情况处理switch(cell.getCellType()){caseXSSFCell.CELL_TYPE_NUMERIC://处理数值带{.0}问题value=Double.valueOf(String.valueOf(cell)).longValue();break;default:value=cell.toString();}linked.add(value);}if(linked.size()!=0){list.add(linked);}}returnlist;}

3、文件创建

publicstaticvoidcreateExcel(StringexcelName,String[]headList,List<List<Object>>dataList)throwsException{//创建Excel工作簿XSSFWorkbookworkbook=newXSSFWorkbook();XSSFSheetsheet=workbook.createSheet();//创建表头XSSFRowrow=sheet.createRow(0);for(inti=0;i<headList.length;i++){XSSFCellcell=row.createCell(i);cell.setCellType(XSSFCell.CELL_TYPE_STRING);cell.setCellValue(headList[i]);}//添加数据for(intline=0;line<dataList.size();line++){XSSFRowrowData=sheet.createRow(line+1);List<Object>data=dataList.get(line);for(intj=0;j<headList.length;j++){XSSFCellcell=rowData.createCell(j);cell.setCellType(XSSFCell.CELL_TYPE_STRING);cell.setCellValue((data.get(j)).toString());}}FileOutputStreamfos=newFileOutputStream(excelName);workbook.write(fos);fos.flush();fos.close();}

4、文件导出

publicstaticvoidexportExcel(String[]headList,List<List<Object>>dataList,OutputStreamoutputStream)throwsException{//创建Excel工作簿XSSFWorkbookworkbook=newXSSFWorkbook();XSSFSheetsheet=workbook.createSheet();//创建表头XSSFRowrow=sheet.createRow(0);for(inti=0;i<headList.length;i++){XSSFCellcell=row.createCell(i);cell.setCellType(XSSFCell.CELL_TYPE_STRING);cell.setCellValue(headList[i]);}//添加数据for(intline=0;line<dataList.size();line++){XSSFRowrowData=sheet.createRow(line+1);List<Object>data=dataList.get(line);for(intj=0;j<headList.length;j++){XSSFCellcell=rowData.createCell(j);cell.setCellType(XSSFCell.CELL_TYPE_STRING);cell.setCellValue((data.get(j)).toString());}}workbook.write(outputStream);outputStream.flush();outputStream.close();}

5、文件导出接口

@RestControllerpublicclassExcelWeb{@RequestMapping("/web/outExcel")publicvoidoutExcel(HttpServletResponseresponse)throwsException{StringexportName="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=newString[]{"用户ID","用户名","手机号"};ExcelUtil.exportExcel(headList,dataList,response.getOutputStream());}}

三、PDF文件管理

1、IText依赖

iText是一种生成PDF报表的Java组件。通过在服务器端使用页面或API封装生成PDF报表,客户端可以通过超链接直接显示或下载到本地,在系统开发中通常用来生成比较正式的报告或者合同类的电子文档。

<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二次封装

首先对于Itext提供的API做一下表格、段落、图片等基础样式的二次封装,可以更好的适配业务。

publicclassPdfFontUtil{privatePdfFontUtil(){}/***段落样式获取*/publicstaticParagraphgetParagraph(Stringcontent,Fontfont,Integeralignment){Paragraphparagraph=newParagraph(content,font);if(alignment!=null&&alignment>=0){paragraph.setAlignment(alignment);}returnparagraph;}/***图片样式*/publicstaticImagegetImage(StringimgPath,floatwidth,floatheight)throwsException{Imageimage=Image.getInstance(imgPath);image.setAlignment(Image.MIDDLE);if(width>0&&height>0){image.scaleAbsolute(width,height);}returnimage;}/***表格生成*/publicstaticPdfPTablegetPdfPTable01(intnumColumns,floattotalWidth)throwsException{//表格处理PdfPTabletable=newPdfPTable(numColumns);//设置表格宽度比例为%100table.setWidthPercentage(100);//设置宽度:宽度平均table.setTotalWidth(totalWidth);//锁住宽度table.setLockedWidth(true);//设置表格上面空白宽度table.setSpacingBefore(10f);//设置表格下面空白宽度table.setSpacingAfter(10f);//设置表格默认为无边框table.getDefaultCell().setBorder(0);table.setPaddingTop(50);table.setSplitLate(false);returntable;}/***表格内容*/publicstaticPdfPCellgetPdfPCell(Phrasephrase){returnnewPdfPCell(phrase);}/***表格内容带样式*/publicstaticvoidaddTableCell(PdfPTabledataTable,Fontfont,List<String>cellList){for(Stringcontent:cellList){dataTable.addCell(getParagraph(content,font,-1));}}}

3、生成PDF文件

这里基于上面的工具类,画一个PDF页面作为参考。

publicclassPdfPage01{//基础配置privatestaticStringPDF_SITE="F:\\file-type\\PDF页面2020-01-15.pdf";privatestaticStringFONT="C:/Windows/Fonts/simhei.ttf";privatestaticStringPAGE_TITLE="PDF数据导出报告";//基础样式privatestaticFontTITLE_FONT=FontFactory.getFont(FONT,BaseFont.IDENTITY_H,20,Font.BOLD);privatestaticFontNODE_FONT=FontFactory.getFont(FONT,BaseFont.IDENTITY_H,15,Font.BOLD);privatestaticFontBLOCK_FONT=FontFactory.getFont(FONT,BaseFont.IDENTITY_H,13,Font.BOLD,BaseColor.BLACK);privatestaticFontINFO_FONT=FontFactory.getFont(FONT,BaseFont.IDENTITY_H,12,Font.NORMAL,BaseColor.BLACK);privatestaticFontCONTENT_FONT=FontFactory.getFont(FONT,BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);privatestaticvoidcreatePdfPage()throwsException{//创建文档Documentdocument=newDocument();PdfWriterwriter=PdfWriter.getInstance(document,newFileOutputStream(PDF_SITE));document.open();//报告标题document.add(PdfFontUtil.getParagraph(PAGE_TITLE,TITLE_FONT,1));document.add(PdfFontUtil.getParagraph("\n商户名称:XXX科技有限公司",INFO_FONT,-1));document.add(PdfFontUtil.getParagraph("\n生成时间:2020-01-15\n\n",INFO_FONT,-1));//报告内容//段落标题+报表图document.add(PdfFontUtil.getParagraph("城市数据分布统计",NODE_FONT,-1));document.add(PdfFontUtil.getParagraph("\n·可视化图表\n\n",BLOCK_FONT,-1));//设置图片宽高floatdocumentWidth=document.getPageSize().getWidth()-document.leftMargin()-document.rightMargin();floatdocumentHeight=documentWidth/580*320;document.add(PdfFontUtil.getImage("F:\\file-type\\myChart.jpg",documentWidth-80,documentHeight-80));//数据表格document.add(PdfFontUtil.getParagraph("\n·数据详情\n\n",BLOCK_FONT,-1));PdfPTabledataTable=PdfFontUtil.getPdfPTable01(4,400);//设置表格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·报表描述\n\n",BLOCK_FONT,-1));document.add(PdfFontUtil.getParagraph("数据报告可以监控每天的推广情况,"+"可以针对不同的数据表现进行分析,以提升推广效果。",CONTENT_FONT,-1));document.newPage();document.close();writer.close();}privatestaticList<List<String>>getTableData(){List<List<String>>tableDataList=newArrayList<>();for(inti=0;i<3;i++){List<String>tableData=newArrayList<>();tableData.add("浙江"+i);tableData.add("杭州"+i);tableData.add("276"+i);tableData.add("33.3%");tableDataList.add(tableData);}returntableDataList;}privatestaticList<String>tableHead(){List<String>tableHeadList=newArrayList<>();tableHeadList.add("省份");tableHeadList.add("城市");tableHeadList.add("数量");tableHeadList.add("百分比");returntableHeadList;}publicstaticvoidmain(String[]args)throwsException{createPdfPage();}}

4、页面效果

四、网页转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、编写页面样式

<!DOCTYPEhtml><htmllang="en"xmlns:th="http://www.w3.org/1999/xhtml"><head><metacharset="UTF-8"/><title>Title</title><style>body{font-family:SimSun;}</style></head><body>项目信息:<br/>名称:${name}<br/>作者:${author}<br/><br/><imgsrc="https://img2018.cnblogs.com/blog/1691717/201906/1691717-20190603213911854-1098366582.jpg"/><br/></body></html>

3、核心配置类

publicclassPageConfig{privatestaticfinalStringDEST="F:\\file-type\\HTML页面2020-01-15.pdf";privatestaticfinalStringHTML="/pdf_page_one.html";privatestaticfinalStringFONT="C:/Windows/Fonts/simsun.ttc";privatestaticConfigurationfreemarkerCfg=null;static{freemarkerCfg=newConfiguration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);//freemarker的模板目录try{Stringpath="TODO:模板路径{自定义}";freemarkerCfg.setDirectoryForTemplateLoading(newFile(path));}catch(IOExceptione){e.printStackTrace();}}/***创建文档*/privatestaticvoidcreatePdf(Stringcontent,Stringdest)throwsException{Documentdocument=newDocument();PdfWriterwriter=PdfWriter.getInstance(document,newFileOutputStream(dest));document.open();XMLWorkerFontProviderfontImp=newXMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);fontImp.register(FONT);XMLWorkerHelper.getInstance().parseXHtml(writer,document,newByteArrayInputStream(content.getBytes()),null,Charset.forName("UTF-8"),fontImp);document.close();}/***页面渲染*/privatestaticStringfreeMarkerRender(Map<String,Object>data,StringhtmlTmp)throwsException{Writerout=newStringWriter();Templatetemplate=freemarkerCfg.getTemplate(htmlTmp,"UTF-8");template.process(data,out);out.flush();out.close();returnout.toString();}/***方法入口*/publicstaticvoidmain(String[]args)throwsException{Map<String,Object>data=newHashMap<>();data.put("name","smile");data.put("author","知了");Stringcontent=PageConfig.freeMarkerRender(data,HTML);PageConfig.createPdf(content,DEST);}}

4、转换效果图

五、源代码地址

文中涉及文件类型,在该章节源码ware18-file-parent/case-file-type目录下。

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

以上就是SpringBoot框架如何管理Excel和PDF的详细内容,更多关于SpringBoot 管理Excel和PDF的资料请关注其它相关文章!

可以以心感悟,以此沉淀,足矣;耳听佳音,目极美好,

SpringBoot框架如何操作Excel和PDF

相关文章:

你感兴趣的文章:

标签云: