目录

    一、文档类型简介

    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、文件读取

    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 表格内容
        xssfsheet sheet = xwb.getsheetat(0);
        // 读取行数:不读取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 ;
                // 这里需根据实际业务情况处理
                switch (cell.getcelltype()) {
                    case xssfcell.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);
            }
        }
        return list;
    }

    3、文件创建

    public static void createexcel(string excelname, string[] headlist,list<list<object>> datalist)
            throws exception {
        // 创建 excel 工作簿
        xssfworkbook workbook = new xssfworkbook();
        xssfsheet sheet = workbook.createsheet();
        // 创建表头
        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]);
        }
        //添加数据
        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、文件导出

    public static void exportexcel(string[] headlist, list<list<object>> datalist,
                                   outputstream outputstream) throws exception {
        // 创建 excel 工作簿
        xssfworkbook workbook = new xssfworkbook();
        xssfsheet sheet = workbook.createsheet();
        // 创建表头
        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]);
        }
        //添加数据
        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、文件导出接口

    @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", "用户名", "手机号"} ;
            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做一下表格、段落、图片等基础样式的二次封装,可以更好的适配业务。

    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);
            // 设置表格宽度比例为%100
            table.setwidthpercentage(100);
            // 设置宽度:宽度平均
            table.settotalwidth(totalwidth);
            // 锁住宽度
            table.setlockedwidth(true);
            // 设置表格上面空白宽度
            table.setspacingbefore(10f);
            // 设置表格下面空白宽度
            table.setspacingafter(10f);
            // 设置表格默认为无边框
            table.getdefaultcell().setborder(0);
            table.setpaddingtop(50);
            table.setsplitlate(false);
            return table ;
        }
        /**
         * 表格内容
         */
        public static pdfpcell getpdfpcell (phrase phrase){
            return new pdfpcell (phrase) ;
        }
        /**
         * 表格内容带样式
         */
        public static void addtablecell (pdfptable datatable,font font,list<string> celllist){
            for (string content:celllist) {
                datatable.addcell(getparagraph(content,font,-1));
            }
        }
    }

    3、生成pdf文件

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

    public class pdfpage01 {
        // 基础配置
        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数据导出报告" ;
        // 基础样式
        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 {
            // 创建文档
            document document = new document();
            pdfwriter writer = pdfwriter.getinstance(document, new fileoutputstream(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)) ;
            // 设置图片宽高
            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)) ;
            // 数据表格
            document.add(pdffontutil.getparagraph("\n· 数据详情\n\n",block_font,-1)) ;
            pdfptable datatable = 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();
        }
        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("数量") ;
            tableheadlist.add("百分比") ;
            return tableheadlist ;
        }
        public static void main(string[] args) throws exception {
            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、编写页面样式

    <!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>
    项目信息:<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();
            }
        }
        /**
         * 创建文档
         */
        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、转换效果图

    五、源代码地址

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

    github·地址

    gitee·地址

    以上就是springboot框架如何管理excel和pdf的详细内容,更多关于springboot 管理excel和pdf的资料请关注www.887551.com其它相关文章!