【POI】列表数据导出word、pdf、excel格式文档

package com.grid.util;

import com.grid.pojo.databean.monitor.SimpleDataBean;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ExportUtils
 * @Description: TODO
 * @Author Winy
 * @Date 2022/03/31
 * @Version V1.0.0
 * Modification History:
 * Date                Author          Version            Description
 * ----------------------------------------------------------------------*
 * 2022/03/31        Winy          v1.0.0             初次创建
 **/
public class ExportUtils {

    public static void main(String[] args) throws FileNotFoundException {
        List<SimpleDataBean> list=new ArrayList<>();
        for (int i=0;i<100000;i++){
            list.add(new SimpleDataBean(Float.parseFloat(Math.random()+""),"2021-12-12 03:00:00"));
        }
        String filename="workbook111.pdf";
        FileOutputStream out =  new FileOutputStream("E:/"+filename);
        export(list,new String[]{"value","time"},new String[]{"数据","时间"},"pdf",out);
    }

    /**
     * 列表导出多格式文档
     *  @param list 数据源
     * @param param 参数 数据源中的属性名称
     * @param topName 列名
     * @param downtype 文件格式 pdf,excel,word
     * @param out 输出流
     */
    public static <T> void export(List<T> list, String[] param, String[] topName, String downtype, OutputStream out) {
        try {
            switch (downtype) {
                case "excel":
                    exportExcel(objectToMap(list),param,topName,out);
                    return;
                case "pdf":
                    exportPdf(objectToMap(list),param,topName,out);
                    return;
                case "word":
                    exportWord(objectToMap(list),param,topName,out);
            }
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void exportExcel(List<Map<String, Object>> list, String[] param, String[] topName, OutputStream out) {
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();
        // 表头加粗居中样式
        HSSFCellStyle style = wb.createCellStyle();
        org.apache.poi.ss.usermodel.Font f = wb.createFont();
        f.setBold(true);
        style.setFont(f);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直居中
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);


        // 内容左对齐,宽度自适应
        HSSFCellStyle contentS = wb.createCellStyle();
        contentS.setAlignment(CellStyle.ALIGN_CENTER);
        contentS.setWrapText(true);
        contentS.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直居中
        contentS.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        contentS.setBorderTop(HSSFCellStyle.BORDER_THIN);
        contentS.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        contentS.setBorderRight(HSSFCellStyle.BORDER_THIN);

        HSSFRow row = sheet.createRow(0);
        //存储最大列宽
        Map<Integer, Integer> maxWidth = new HashMap<>();

        //写入表头
        for (int i = 0; i < topName.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(topName[i]);
            cell.setCellStyle(style);
            maxWidth.put(i, cell.getStringCellValue().getBytes().length * 256 + 200);
        }


        //写入数据
        for (int i = 0; i < list.size(); i++) {
            row = sheet.createRow(i+1);
            Map<String, Object> m = list.get(i);
            for (int j = 0; j < param.length; j++) {
                HSSFCell cell = row.createCell(j);
                cell.setCellStyle(contentS);
                cell.setCellValue(m.get(param[j]) + "");
                sheet.setColumnWidth(j, 8 * 512);
                int length = cell.getStringCellValue().getBytes().length * 256 + 200;
                //这里把宽度最大限制到15000
                if (length > 15000) {
                    length = 15000;
                }
                maxWidth.put(j, Math.max(length, maxWidth.get(j)));
            }
        }
        // 列宽自适应
        for (int i = 0; i < topName.length; i++) {
            sheet.setColumnWidth(i, maxWidth.get(i));
        }
        try {
            wb.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void exportPdf(List<Map<String, Object>> list, String[] param, String[] topName, OutputStream out) {
        // 第一步,实例化一个document对象
        Document document = new Document();
        // 第三步,设置字符
        BaseFont bfChinese = null;
        try {
            bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }
        Font fontZH = new Font(bfChinese, 12.0F, 0);
        // 第四步,将pdf文件输出到磁盘
        try {
            PdfWriter.getInstance(document, out);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        // 第五步,打开生成的pdf文件
        document.open();
        // 第六步,设置内容
        // 创建table,注意这里的2是两列的意思,下面通过table.addCell添加的时候必须添加整行内容的所有列
        PdfPTable table = new PdfPTable(topName.length);
        table.setWidthPercentage(100.0F);
        table.setHeaderRows(1);
        table.getDefaultCell().setHorizontalAlignment(1);
        for (String p:topName) {
            table.addCell(new Paragraph(p, fontZH));
        }
        for (Map<String,Object> l:list) {
            for (String p:param) {
                table.addCell(new Paragraph(l.get(p).toString(), fontZH));
            }
        }
        try {
            document.add(table);
            document.add(new Paragraph("\n"));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        // 第七步,关闭document
        document.close();
    }

    private static void exportWord(List<Map<String, Object>> list, String[] param, String[] topName, OutputStream out) {
        XWPFDocument document=new XWPFDocument();
        XWPFTable table = document.createTable();
        //列宽自动分割
        CTTblWidth infoTableWidth=table.getCTTbl().addNewTblPr().addNewTblW();
        infoTableWidth.setType(STTblWidth.DXA);
        infoTableWidth.setW(BigInteger.valueOf(9072));

        //自适应窗口

        //第一行 列名
        XWPFTableRow row_top=table.getRow(0);
        for (int i=0;i<topName.length;i++) {
            XWPFTableCell cell=row_top.getCell(i);
            if (cell==null)
                cell=row_top.addNewTableCell();
            cell.setText(topName[i]);
        }

        //填充数据
        for (Map<String,Object> l:list) {
            XWPFTableRow row=table.createRow();
            for (int i=0;i<topName.length;i++) {
                row.getCell(i).setText(l.get(param[i]).toString());
            }
        }
        try {
            document.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }




    /**
     * List<object>转List<map>
     */
    private static <StationDeviceDataBean> List<Map<String, Object>> objectToMap(List<StationDeviceDataBean> reorder) {
        List<Map<String, Object>> lm = new ArrayList<>();
        try {
            for (Object obj : reorder) {
                if (obj == null) {
                    return null;
                }
                Map<String, Object> map = new HashMap<>();
                Field[] declaredFields = obj.getClass().getDeclaredFields();
                for (Field field : declaredFields) {
                    field.setAccessible(true);
                    map.put(field.getName(), field.get(obj));
                }
                Field[] sFields = obj.getClass().getSuperclass().getDeclaredFields();
                for (Field field : sFields) {
                    field.setAccessible(true);
                    map.put(field.getName(), field.get(obj));
                }
                lm.add(map);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return lm;
    }
    public static String getSuffix(String downType) {
        switch (downType){
            case "pdf":return "pdf";
            case "excel":return "xlsx";
            case "word":return "docx";
        }
        return "xlsx";
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Winy_26

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值