java实现导出表单word与pdf功能

java实现导出表单word与pdf功能

前文:

实现导出功能有很多方法,可以使用freemarker定义模板修改其为xml,在改成ftl,需要可以私信我,

本文用的是itextpdf自定义模板,虽然自己制表比较繁琐但是简单易懂

环境

idea

依赖·

<!-- 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>
<!-- 写word -->
<dependency>
    <groupId>com.lowagie</groupId>
    <artifactId>itext</artifactId>
    <version>2.1.7</version>
</dependency>
<dependency>
    <groupId>com.lowagie</groupId>
    <artifactId>itext-rtf</artifactId>
    <version>2.1.7</version>
</dependency>

具体实现

controller

控制层,根据自己业务编写重要的是调用对应的导出方法


//数据导出word
@PostMapping("/word")
public ResultBean word(@RequestBody String list) {
    List<SampleIndexDTO> samples = JSON.parseArray(list, SampleIndexDTO.class);
    try {
        GenerateWord.word(samples);
    } catch (Exception e) {
        e.printStackTrace();
        throw new ExportException("数据导出word失败");
    }
    return ResultBean.success("导出word成功");
}
//数据导出pdf
    @PostMapping("/pdf")
    public ResultBean pdf(@RequestBody String list) {
        List<SampleIndexDTO> samples = JSON.parseArray(list, SampleIndexDTO.class);
        try {
            PdfUtils.downloadPdf(samples);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExportException("数据导出pdf失败");
        }
        return ResultBean.success("导出pdf成功");
    }

这里传入的list对象集合,添加到表格中

word方法


import com.df.samplesub.entity.SampleIndexDTO;
import com.lowagie.text.Font;
import com.lowagie.text.Rectangle;
import com.lowagie.text.*;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.rtf.RtfWriter2;

import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

/**
 * @Description: 生成列表word
 * @Param:
 * @return:
 * @Author:
 * @Date: 2021/6/2
 */
public class GenerateWord {
    public static void word(List list) throws Exception {
        BaseFont bfChinese = BaseFont.createFont("Courier", "Cp1252", BaseFont.NOT_EMBEDDED);
        File file = null;
        //设置纸张的大小对象
        Rectangle rectangle = new Rectangle(PageSize.A4);
        // 创建word文档,并旋转,使其横向
        Document document = new Document(rectangle.rotate());

        //创建文件夹
        String filePar = null;
        String file1 = "D:";

        filePar = file1;// 文件夹路径
        File myPath = new File(filePar);
        file = new File(filePar + "/样本送检系统样品列表" + YearUtil.getStringDate() + ".doc");
        if (!myPath.exists()) {
            myPath.mkdir();
        }
        RtfWriter2.getInstance(document, new FileOutputStream(file));
        document.open();
        //报表标题
        Paragraph headTitle = new Paragraph("样本送检系统样品列表");
        Font headFont = new Font(bfChinese);
        headFont.setSize(22);
        headFont.setStyle(Font.BOLD);
        headTitle.setFont(headFont);
        headTitle.setAlignment(1);//居中
        document.add(headTitle);

        //正文表格
        PdfPTable table = new PdfPTable(10);
        //设置表格宽度
        table.setWidths(new float[]{9f, 9f, 9f, 20f, 20f, 20f, 20f, 9f, 9f, 9f});
        table.setTotalWidth(114);

        //设置表头字体样式
        Font tableHeadFont = new Font(bfChinese);//表头字体样式
        tableHeadFont.setSize(10.5f);//设置表头字体为五号字体
        tableHeadFont.setStyle(Font.BOLD);//加粗
//根据需要列
        //表头第一列:序号
        PdfPCell headCell1 = new PdfPCell();
        Paragraph headCell1Phrase = new Paragraph("序号");
        headCell1Phrase.setFont(tableHeadFont);
        headCell1.setPhrase(headCell1Phrase);
        headCell1Phrase.setAlignment(1);
        headCell1.setHorizontalAlignment(1);

        //表头第二列:样本类型
        PdfPCell headCell2 = new PdfPCell();
        Paragraph headCell2Phrase = new Paragraph("样本类型");
        headCell2Phrase.setFont(tableHeadFont);
        headCell2.setPhrase(headCell2Phrase);
        headCell2Phrase.setAlignment(1);
        headCell2.setHorizontalAlignment(1);

        //表头第三列:样本数量
        PdfPCell headCell3 = new PdfPCell();
        Paragraph headCell3Phrase = new Paragraph("样本数量");
        headCell3Phrase.setFont(tableHeadFont);
        headCell3.setPhrase(headCell3Phrase);
        headCell3Phrase.setAlignment(1);
        headCell3.setHorizontalAlignment(1);

        //表头第四列:送检单位
        PdfPCell headCell4 = new PdfPCell();
        Paragraph headCell4Phrase = new Paragraph("送检单位");
        headCell4Phrase.setFont(tableHeadFont);
        headCell4.setPhrase(headCell4Phrase);
        headCell4Phrase.setAlignment(1);
        headCell4.setHorizontalAlignment(1);

        //表头第五列:送检日期
        PdfPCell headCell5 = new PdfPCell();
        Paragraph headCell5Phrase = new Paragraph("送检日期");
        headCell5Phrase.setFont(tableHeadFont);
        headCell5.setPhrase(headCell5Phrase);
        headCell5Phrase.setAlignment(1);
        headCell5.setHorizontalAlignment(1);

        //表头第六列:收样日期
        PdfPCell headCell6 = new PdfPCell();
        Paragraph headCell6Phrase = new Paragraph("收样日期");
        headCell6Phrase.setFont(tableHeadFont);
        headCell6.setPhrase(headCell6Phrase);
        headCell6Phrase.setAlignment(1);
        headCell6.setHorizontalAlignment(1);

        //表头第七列:出报告日期
        PdfPCell headCell7 = new PdfPCell();
        Paragraph headCell7Phrase = new Paragraph("出报告日期");
        headCell7Phrase.setFont(tableHeadFont);
        headCell7.setPhrase(headCell7Phrase);
        headCell7Phrase.setAlignment(1);
        headCell7.setHorizontalAlignment(1);


        //表头第八列:有无无法判断
        PdfPCell headCell8 = new PdfPCell();
        Paragraph headCell8Phrase = new Paragraph("有无无法判断");
        headCell8Phrase.setFont(tableHeadFont);
        headCell8.setPhrase(headCell8Phrase);
        headCell8Phrase.setAlignment(1);
        headCell8.setHorizontalAlignment(1);

        //表头第九列:收样样品是否破损
        PdfPCell headCell9 = new PdfPCell();
        Paragraph headCell9Phrase = new Paragraph("收样样品是否破损");
        headCell9Phrase.setFont(tableHeadFont);
        headCell9.setPhrase(headCell9Phrase);
        headCell9Phrase.setAlignment(1);
        headCell9.setHorizontalAlignment(1);

        //表头第十列:地区
        PdfPCell headCell10 = new PdfPCell();
        Paragraph headCell10Phrase = new Paragraph("地区");
        headCell10Phrase.setFont(tableHeadFont);
        headCell10.setPhrase(headCell10Phrase);
        headCell10Phrase.setAlignment(1);
        headCell10.setHorizontalAlignment(1);


        table.addCell(headCell1);
        table.addCell(headCell2);
        table.addCell(headCell3);
        table.addCell(headCell4);
        table.addCell(headCell5);
        table.addCell(headCell6);
        table.addCell(headCell7);
        table.addCell(headCell8);
        table.addCell(headCell9);
        table.addCell(headCell10);
        //表头添加完毕

        //添加表格体
      /*  for(int i=0; i<1000; i++) {
            table.addCell("QW");
        }*/
        for (List sampleIndexDTO : list) {
            //注意此方法传入的是String类型
            table.addCell(String.valueOf(sampleIndexDTO.getId()));//ID
            table.addCell(sampleIndexDTO.getSampleType());//样本类型
            table.addCell(String.valueOf(sampleIndexDTO.getSampleQuantity()));//样本数量
            table.addCell(sampleIndexDTO.getSubmissionUnit());//送检单位
            table.addCell(sampleIndexDTO.getCheckTime());//送检日期
            table.addCell(sampleIndexDTO.getReceiveSampleTime());//收样日期
            table.addCell(sampleIndexDTO.getReportTime());//出报告日期
            table.addCell(String.valueOf(sampleIndexDTO.getClear()));//有无无法判断
            table.addCell(String.valueOf(sampleIndexDTO.getBroken()));//是否破损
            table.addCell(sampleIndexDTO.getLocation());//地区
        }
       //添加进内容
        document.add(table);


        //页脚段落
        Paragraph paraFooter = new Paragraph();
        Font font = new Font();
        //页脚的字体大小
        font.setSize(12f);
        font.setColor(new Color(0, 0, 0));
        paraFooter.setFont(font);
        paraFooter.setAlignment("center");
        //页脚的段落和是否有页码
        HeaderFooter footer = new HeaderFooter(paraFooter, true);
        //页脚的对齐方式(应该在footer设置而不是段落中设置)
        footer.setAlignment(1);
        document.setFooter(footer);

        document.close();
    }

    public static void main(String[] args) throws Exception {

    }
}

导出pdf


import com.df.samplesub.entity.SampleIndexDTO;
import com.itextpdf.text.Font;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.lowagie.text.Cell;
import com.lowagie.text.Table;
import com.lowagie.text.rtf.RtfWriter2;

import javax.servlet.ServletOutputStream;
import java.awt.*;
import java.io.*;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 
 * @Date: 2021/06/02/9:28
 * @Description:生成pdf
 */
public class PdfUtils {
    public static String downloadPdf(List list) throws Exception {
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        //生成pdf
        Document document = new Document(PageSize.A4, 25, 25, 25, 25);

        //创建文件夹
        String filePar = null;
        String file1 = "D:";

        filePar = file1;// 文件夹路径
        File myPath = new File(filePar);
        file = new File(filePar + "/样本送检系统样品列表" + YearUtil.getStringDate() + ".pdf");
        if (!myPath.exists()) {
            myPath.mkdir();
        }
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        //设置中文字体
        BaseFont bfChinese = null;// FontFactory.getFont(FontFactory.COURIER,
        // 14, Font.BOLD, new CMYKColor(0, 255, 0, 0);//大小,粗细,颜色
        try {
            bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
                    BaseFont.NOT_EMBEDDED);
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
        //设置字体
        Font f10 = new Font(bfChinese, 10, Font.NORMAL);
        Font f12 = new Font(bfChinese, 12, Font.NORMAL);
        Font f26 = new Font(bfChinese, 26, Font.NORMAL);//一号字体
        //创建标题
        Paragraph title1 = new Paragraph("样本送检系统样品列表", f26);
        title1.setAlignment(Element.ALIGN_CENTER);
        Chapter chapter1 = new Chapter(title1, 1);
        chapter1.setNumberDepth(0);
        Section section1 = chapter1;

        // 创建11列的表格,根据需求自定义
        int colNumber = 10;
        PdfPTable t = new PdfPTable(colNumber);
        //设置段落上下空白
        t.setSpacingBefore(25);
        t.setSpacingAfter(25);
        t.setHorizontalAlignment(Element.ALIGN_CENTER);// 居左
        float[] cellsWidth = {0.1f, 0.2f, 0.2f, 0.2f, 0.4f, 0.4f, 0.4f, 0.2f, 0.3f, 0.1f}; // 定义表格的宽度
        t.setWidths(cellsWidth);// 单元格宽度
        t.setTotalWidth(500f);//表格的总宽度
        t.setWidthPercentage(100);// 表格的宽度百分比
        //设置表头
        PdfPCell c1 = new PdfPCell(new Paragraph("序号", f12));
        t.addCell(c1);
        PdfPCell c2 = new PdfPCell(new Paragraph("样本类型", f12));
        t.addCell(c2);
        PdfPCell c3 = new PdfPCell(new Paragraph("样本数量", f12));
        t.addCell(c3);

        PdfPCell c4 = new PdfPCell(new Paragraph("送检单位", f12));
        t.addCell(c4);
        PdfPCell c5 = new PdfPCell(new Paragraph("送检日期", f12));
        t.addCell(c5);
        PdfPCell c6 = new PdfPCell(new Paragraph("收样日期", f12));
        t.addCell(c6);
        PdfPCell c7 = new PdfPCell(new Paragraph("出报告日期", f12));
        t.addCell(c7);
        PdfPCell c8 = new PdfPCell(new Paragraph("有无无法判断", f12));
        t.addCell(c8);
        PdfPCell c9 = new PdfPCell(new Paragraph("收样样品是否破损", f12));
        t.addCell(c9);
        PdfPCell c10 = new PdfPCell(new Paragraph("地区", f12));
        t.addCell(c10);

        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");

        for (List sampleIndexDTO : list) {
            t.addCell(String.valueOf(sampleIndexDTO.getId()));//ID
            t.addCell(sampleIndexDTO.getSampleType());//样本类型
            t.addCell(String.valueOf(sampleIndexDTO.getSampleQuantity()));//样本数量
            t.addCell(sampleIndexDTO.getSubmissionUnit());//送检单位
            t.addCell(sampleIndexDTO.getCheckTime());//送检日期
            t.addCell(sampleIndexDTO.getReceiveSampleTime());//收样日期
            t.addCell(sampleIndexDTO.getReportTime());//出报告日期
            t.addCell(String.valueOf(sampleIndexDTO.getClear()));//有无无法判断
            t.addCell(String.valueOf(sampleIndexDTO.getBroken()));//是否破损
            t.addCell(sampleIndexDTO.getLocation());//地区
        }

        section1.add(t);
        document.add(chapter1);
        document.close();
        /*******pdf文件生成结束*********/
    }

}

运行截图

在这里插入图片描述

代码能跑就行,优化后续进行

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值