Java 读取 Excel 文件内容, 根据 pdf 模板动态生成对应的 pdf 文件

1. 下载 adobe acrobat 

https://www.cr173.com/soft/11135.html

2. 编辑 pdf 模板

  • 1用 acrobat 打开 pdf 

  • 编辑模板

  • 添加表单元素保存模板 “moban-1.pdf”

 

3. Java 动态生成 pdf

  • pom 依赖
        <!-- pdf 依赖-->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.10</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

         <!--POI解析-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
  • 实体类对象(属性命名方式,请大家不要模仿(不规范))

import lombok.Data;
import lombok.experimental.Accessors;

@SuppressWarnings("all")
@Data
@Accessors(chain = true)
public class ObjSoure {

    //0
    private String name;

    //1
    private String num;

    //2
    private String bisaiName;

    //3
    private String desc;

    //4
    private String shengfen;

    //5
    private String kaodian;

    //6
    private String jibie;

    //7
    private String zubie;

    //8
    private String diyichengji;

    //9
    private String diyibaifenbi;

    //10
    private String dierchengji;

    //11
    private String dierbaifenbi;

    //12
    private String zongchenji;

    //13
    private String quanguobaifenbi;

    //14
    private String shengbaifenbi;

    //15
    private String gongbuchengji;
}
  • 读取 excel 文件中的数据(下图为 Excel 数据样例,方法中有好多没有做 校验,后期再补充)


import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 读取Excel文件
 * @Author      yanghanwei
 * @Mail        yanghanwei@geotmt.com
 * @Date        2020/1/5 20:58
 * @Version     v1
 **/
public class ReadExcel {

    XSSFWorkbook wb = null;

    public void  init (){

        try {
            //excel模板路径
            File cfgFile = ResourceUtils.getFile("E:/总分-4发布成绩.xlsx");
            InputStream in = new FileInputStream(cfgFile);
            //读取excel模板
            wb = new XSSFWorkbook(in);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取 Excel 中的数据
     * @return
     */
    public List<ObjSoure> read() {
        List<ObjSoure> list = new ArrayList<ObjSoure>();
        init ();
        //获取sheet表格,及读取单元格内容
        XSSFSheet sheet = null;
        try{
            sheet = wb.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();
            System.out.println(lastRowNum);
            for (int i = 1; i<= lastRowNum; i++) {
                ObjSoure objSoure = new ObjSoure();
                // Excel 中一共有16 列,暂时写死了
                for (int j = 0; j< 16; j++) {
                    String cellValue ="";
                    if(null != sheet.getRow(i).getCell(j)){
                        sheet.getRow(i).getCell(j).setCellType(CellType.STRING);
                        cellValue = sheet.getRow(i).getCell(j).getStringCellValue();
                        linkObj(objSoure, j, cellValue);
                    }
                }
                System.out.println("================ 第"+i+"行完成==============");
                System.out.println(objSoure);
                list.add(objSoure);
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 根据 excel 文件的顺序给对象赋值
     * @param obj
     * @param j
     * @param val
     */
    private void linkObj(ObjSoure obj, int j, String val) {
       switch (j) {
           case 0:
               obj.setName(val);
               break;
           case 1:
               obj.setNum(val);
               break;
           case 2:
               obj.setBisaiName(val);
               break;
           case 3:
               obj.setDesc(val);
               break;
           case 4:
               obj.setShengfen(val);
               break;
           case 5:
               obj.setKaodian(val);
               break;
           case 6:
               obj.setJibie(val);
               break;
           case 7:
               obj.setZubie(val);
               break;
           case 8:
               obj.setDiyichengji(val);
               break;
           case 9:
               obj.setDiyibaifenbi(tranNum(val));
               break;
           case 10:
               obj.setDierchengji(val);
               break;
           case 11:
               obj.setDierbaifenbi(tranNum(val));
               break;
           case 12:
               obj.setZongchenji(val);
               break;
           case 13:
               obj.setQuanguobaifenbi(tranNum(val));
               break;
           case 14:
               obj.setShengbaifenbi(tranNum(val));
               break;
           case 15:
               obj.setGongbuchengji(val);
               break;
           default:
               break;
       }

    }

    /**
     * 百分数的特殊处理
     * @param val
     * @return
     */
    private String tranNum(String val){
        Double b = Double.valueOf(val)* 100;
        return b.intValue() + "%";
    }

    public static void main(String[] args) {
        new ReadExcel().read();
    }
}
  • 基于模板,动态的填充 pdf 模板并生成 新的pdf 文件
public static void fillTemplate() {

        List<ObjSoure> read = new ReadExcel().read();
//        List<ObjSoure> read = new ArrayList<>();
//        read.add(new ObjSoure().setName("张三").setZongchenji("800").setQuanguobaifenbi("20%").setShengbaifenbi("30%").setShengfen("shanxi"));

        System.out.println(read);
        // 模板路径
        String templatePath = "E:/moban-1.pdf";
        if(null != read && !read.isEmpty()){
            for(int a = 0; a < read.size(); a++){
                ObjSoure obj = read.get(a);
                // 生成的新文件路径
                String newPDFPath = "E:/学生成绩/" + obj.getName().trim() + "-"+ obj.getShengfen().trim() + ".pdf";
                PdfReader reader;
                FileOutputStream out;
                ByteArrayOutputStream bos;
                PdfStamper stamper;
                try {
                    out = new FileOutputStream(newPDFPath);// 输出流
                    reader = new PdfReader(templatePath);// 读取pdf模板
                    bos = new ByteArrayOutputStream();
                    stamper = new PdfStamper(reader, bos);
                    AcroFields form = stamper.getAcroFields();
                    String[] str = { obj.getName(),obj.getNum(), obj.getBisaiName(), obj.getDesc(), obj.getShengfen(), obj.getKaodian(), obj.getJibie(), obj.getZubie(),
                            obj.getDiyichengji(), obj.getDiyibaifenbi(), obj.getDierchengji(), obj.getDierbaifenbi(),
                            obj.getZongchenji(), obj.getQuanguobaifenbi(),obj.getShengbaifenbi(), obj.getGongbuchengji()};
                    int i = 0;
                    java.util.Iterator<String> it = form.getFields().keySet().iterator();
                    while (it.hasNext()) {
                        String name = it.next().toString();
                        System.out.println(name + "============" + str[Integer.parseInt(name)]);
                        form.setField(name, str[Integer.parseInt(name)]);
                    }
                    stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑,一定要设为true
                    stamper.close();
                    Document doc = new Document();
                    PdfCopy copy = new PdfCopy(doc, out);
                    doc.open();
                    PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
                    copy.addPage(importPage);
                    doc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (DocumentException e) {
                    e.printStackTrace();
                }
            }
        }

    }

 

  • 启动 main(测试)
 public static void main(String[] args) {
     fillTemplate();
 }
  • 生成的 PDF 文件展示

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值