利用java实现excel转pdf文件

在有些需求当中我们需要抓取字段并且填充到excel表格里面,最后将excel表格转换成pdf格式进行输出,我第一次接触这个需求时,碰到几个比较棘手的问题,现在一一列出并且提供解决方案。

1:excel转pdf出现乱码:

    第一次excel转pdf是成功的,第二次开始后面皆是乱码,是因为我的pdf转excel方法出现的问题,解决办法是采用java自身底层的方法(详见下方代码)。

 public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("license.xml"); //  license.xml应放在..\WebRoot\WEB-INF\classes路径下
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {               
            e.printStackTrace();
        }
        return result;
    }
    
    
    public static void excelTransferPdf(String excelPath,String pdfPath) {
        if (!getLicense()) {
            System.out.println("license faile");
            return;
        }
        
        try {     
            Workbook wb = new Workbook(excelPath);
            FileOutputStream fileOS = new FileOutputStream(new File(pdfPath));
            wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
            fileOS.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2:excel转pdf出现折行。

  excel转pdf出现折行的情况非常常见,因为在程序运行过程中很多字段是抓取的,你无法判断你的excel转成pdf会有几页,所以这个时候你就不要随意设置excel的预览格式,将excel的单元格式设置自动换行。

3:抓取字段显示结果不完整:。

  当你未设置单元格大小而又没有设置单元格自动换行,比如你的A18单元格里面的字段超过了单元格的长度你还没有设置单元格大小而又没有设置单元格自动换行,就将抓取的字段填充在B18单元格里面,那么打印出来的pdf文件A18单元格超出单元格外的内容是不予显示的,此时你要么将抓取字段填充在C18单元格内要么将更改A18单元格格式

4:excel转PDF字段内容无故中间部分换行:

  这是我碰到的最坑的一个地方,这个时候你只需要在excel单元格里面设置自动换行即可,无需代码强行自动换行(强行换行有可能只出现多行数据只显示一行)。同时你需要如下代码:

/**
     * 得到一个字符串的长度,显示的长度,一个汉字或日韩文长度为1,英文字符长度为0.5
     *
     * @param String
     *            s 需要得到长度的字符串
     * @return int 得到的字符串长度
     */
    public static double getLength(String s) {
        double valueLength = 0;
        if (s == null) {
            return 0;
        }
        String chinese = "[\u4e00-\u9fa5]";
        // 获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1
        for (int i = 0; i < s.length(); i++) {
            // 获取一个字符
            String temp = s.substring(i, i + 1);
            // 判断是否为中文字符
            if (temp.matches(chinese)) {
                // 中文字符长度为2
                valueLength += 2;
            } else {
                // 其他字符长度为1
                valueLength += 1;
            }
        }
        // 进位取整
        return Math.ceil(valueLength);
    }

    /**
     * 根据字符串长度获取行高
     *
     * @param str
     * @return
     */
    public static Float getRowHeight(String str) {

        Integer lineCount = (int) (getLength(str) / 64) + 1;
        if (str.contains("\n")) {
            Integer tempLineCount = 1;
            String[] lines = str.split("\n");
            for (String line : lines) {
                Integer everyLineCount = (int) (getLength(line) / 64) + 1;
                tempLineCount += everyLineCount;
            }
            lineCount = lineCount >= tempLineCount ? lineCount : tempLineCount;
        }
        Float rowHeight = (float) (lineCount * 20);
        return rowHeight;
    }

你需要先获取抓取的字符串的长度,然后通过这个方法计算行高,再将excel需要填充的该行用Java代码设置行高(行高单位是像素),但是如果出现我上面说的字段内容无故中间部分换行,那么你获取的行高就会不足,这个时候你需要改动这个地方----->>>>Float rowHeight = (float) (lineCount * X);  x的值一定要设置的大一行,以防出现这种情况!

 

转载于:https://www.cnblogs.com/lg-wxf/p/9474427.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/279616.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Jmeter HTTP请求后响应数据显示乱码解决方法

Jmeter请求后结果树里无论是text还是html响应数据显示乱码&#xff0c;这是因为jmeter 编码格式配置文件默认不开启导致的&#xff0c;解决方法如下&#xff1a; 1&#xff09;进入jmeter-***\bin目录下&#xff0c;找到jmeter.properties文件&#xff0c;以文本文件形式打开 2…

禁用windows10更新_如何在Windows 10中禁用投影

禁用windows10更新The drop shadows on applications in the Windows 10 preview are really big and suspiciously similar to the ones in OS X, and if they aren’t your speed, you can easily remove them. We actually think they look good, but since somebody out th…

如何访问 Service?- 每天5分钟玩转 Docker 容器技术(99)

前面我们已经学习了如何部署 service&#xff0c;也验证了 swarm 的 failover 特性。不过截止到现在&#xff0c;有一个重要问题还没有涉及&#xff1a;如何访问 service&#xff1f;这就是本节要讨论的问题。 为了便于分析&#xff0c;我们重新部署 web_server。 ① docker se…

sqlyog下载

sqlyog下载&#xff08;附注册码&#xff09;&#xff1a;http://www.onlinedown.net/soft/24926.htm转载于:https://www.cnblogs.com/shujuxiong/p/9474496.html

Linux配置手册(二)配置DHCP服务器

1.检查是否安装DHCP服务器软件 2.挂在RHEL5系统光盘 3.安装DHCP服务软件 4.将模板配置文件复制并覆盖现在的配置文件 5.配置修改dhcpd.conf文件 配置信息 默认租约时间 default-lease-time 最大租约时间 max-lease-time 局域网内所有主机的域名 option domain-name 客户机所使用…

什么是Google Play保护以及如何确保Android安全?

Android is open, flexible, and all about choice. Unfortunately, that flexibility comes more potential security issues. The good news is that Google has a system in place named Play Protect that helps keep Android secure. Android开放&#xff0c;灵活且具有多…

如何使计算机为您读取文档

Since the beginning of the computer age, people have always enjoyed making computers talk to them. These days, that functionality is built right into Windows and you can easily use it to have your PC read documents to you. 自计算机时代开始以来&#xff0c;人…

面试中常问的List去重问题,你都答对了吗?

2019独角兽企业重金招聘Python工程师标准>>> 面试中经常被问到的list如何去重&#xff0c;用来考察你对list数据结构&#xff0c;以及相关方法的掌握&#xff0c;体现你的java基础学的是否牢固。 我们大家都知道&#xff0c;set集合的特点就是没有重复的元素。如果集…

Coolite Toolkit学习笔记五:常用控件Menu和MenuPanel

Coolite Toolkit里的Menu控件和其他的.NET Web控件不一样&#xff0c;如果只是设计好了Menu或是通过程序初始化菜单项&#xff0c;菜单是不会呈现在界面上的&#xff0c;因为Coolite Toolkit规定Menu控件需要一个容器来做依托&#xff0c;而这个让Menu依托的控件就是MenuPanel&…

刚接触git,提交文件时,遇到no changes added to commit

第一次用git 在提交&#xff08;git commit -m add 文件名&#xff09;的时候&#xff0c;遇到了一个no changes added to commit&#xff0c;大体意思是没有将改变的东西提交成功&#xff0c;查了很多博客&#xff0c;才解决这个问题&#xff0c;然后自己也做一下笔记&#…

CSS中!important的使用

本篇文章使用最新的IE10以及firefox与chrome测试&#xff08;截止2013年5月27日22:23:22&#xff09;http://www.cnblogs.com/yudy/archive/2013/05/27/3102825.html CSS的原理&#xff1a; 我们知道&#xff0c;CSS写在不同的地方有不同的优先级&#xff0c; .css文件中的定义…

windows命令提示符_如何个性化Windows命令提示符

windows命令提示符Command line interfaces can be downright boring and always seem to miss out on the fresh coats of paint liberally applied to the rest of Windows. Here’s how to add a splash of color to Command Prompt and make it unique. 命令行界面可能非常…

android-api28转换到api19-不能编译

安装出现错误- rootponkan:/ # pm install /mnt/usb/sda1/app-debug.apkpkg: /mnt/usb/sda1/app-debug.apk Failure [INSTALL_FAILED_OLDER_SDK]查看系统和api版本 rootponkan:/ # getprop ro.build.version.release 5.1.1 rootponkan:/ # getprop ro.build.version.sdk 22将ap…

Java多线程编程 — 锁优化

2019独角兽企业重金招聘Python工程师标准>>> 阅读目录 一、尽量不要锁住方法 二、缩小同步代码块&#xff0c;只锁数据 三、锁中尽量不要再包含锁 四、将锁私有化&#xff0c;在内部管理锁 五、进行适当的锁分解 正文 并发环境下进行编程时&#xff0c;需要使用锁机…

Android Ap 开发 设计模式第六篇:原型模式

Prototype Pattern 名称由来 不是利用类来产生实例对象&#xff0c;而是从一个对象实例产生出另一个新的对象实例 &#xff0c;根据被视为原型的对象实例 &#xff0c;建立起的另一个新的对象实例就称为原型模式&#xff08;Ptototype Pattern&#xff09;。 需求场景 种类过多…

netty实现客户端服务端心跳重连

前言&#xff1a; 公司的加密机调度系统一直使用的是http请求调度的方式去调度&#xff0c;但是会出现网络故障导致某个客户端或者服务端断线的情况&#xff0c;导致很多请求信息以及回执信息丢失的情况&#xff0c;接着我们抛弃了http的方式&#xff0c;改为Tcp的方式去建立客…

为什么您仍然不应该购买《星球大战:前线II》

If you’ve been following video game news at all for the last couple of weeks, you’ve probably heard that EA’s Star Wars: Battlefront II is having some teething troubles. EA has backpedaled to avoid more controversy, but we’re here to say: don’t fall f…

web 后台返回json格式数据的方式(status 406)

1.在类上使用注解 RestController public class HttpComentInterface {} 2.在方法是使用注解 ResponseBody RequestMapping(path "/interface/queryRemote", method RequestMethod.POST) //可以指定请求方式ResponseBody public RemoteCommentResultData queryCo…

OpenStack Juno系列之计算节点搭建

OpenStack Juno系列之计算节点搭建 nova-compute安装配置 -------------------- apt-get install nova-compute sysfsutils 编辑配置文件 vi /etc/nova/nova.conf [DEFAULT] verbose True rpc_backend rabbit rabbit_host controller rabbit_password RABBIT_PASS auth_str…

quantum_如何从Firefox Quantum删除Pocket

quantumFirefox Quantum has deep integration with the Pocket read-it-later service, which is now owned by Mozilla. You’ll see a Pocket page action in the address bar, a “View Pocket List” feature in the Library, and recommended articles from Pocket on th…