Java可视化报表,POI操作word的基本用法

1、API介绍

1、操作Word正文

XWPFDocument代表一个docx文档,其可以用来读docx文档,也可以用来写docx文档

一个文档包含多个段落,一个段落包含多个Runs文本,一个Runs包含多个Run,Run是文档的最小单元

获取所有段落:

List<XWPFParagraph> paragraphs = word.getParagraphs();

获取一个段落中的所有片段Runs:

List<XWPFRun> xwpfRuns = xwpfParagraph.getRuns();

获取一个Runs中的一个Run:

XWPFRun run = xwpfRuns.get(index);

2、操作Word表格

一个文档包含多个表格,一个表格包含多行,一行包含多列单元格

获取所有表格:

List<XWPFTable> xwpfTables = doc.getTables();

获取一个表格中的所有行:

List<XWPFTableRow> xwpfTableRows = xwpfTable.getRows();

获取一行中的所有列:

List<XWPFTableCell> xwpfTableCells = xwpfTableRow.getTableCells();

获取一格里的内容:

List<XWPFParagraph> paragraphs = xwpfTableCell.getParagraphs();
1、word工具类
public class WordUtils {

    /**
     * 导出word工具类
     * @param response
     * @param user
     * @throws Exception
     */
    public static void exportWord(HttpServletResponse response, User user) throws Exception{
        File classpath = new File(ResourceUtils.getFile("classpath:").getPath());
        File file = new File(classpath.getAbsolutePath(), "/word_template/contract_template.docx");
        //读取模板信息
        XWPFDocument document = new XWPFDocument(new FileInputStream(file));
        Map<String, String> map = new HashMap<>(10);
        map.put("userName", user.getUserName());
        map.put("hireDate",new SimpleDateFormat("yyyy-MM-dd").format(user.getHireDate()));
        map.put("address", user.getAddress());

        //处理数据 获取所有段落
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            //获取所有片段
            List<XWPFRun> runs = paragraph.getRuns();
            for (XWPFRun run : runs) {
                String text = run.getText(0);
                for (String s : map.keySet()) {
                    if (text.contains(s)){
                        //替换字段
                        run.setText(text.replaceAll(s,map.get(s)),0);
                    }
                }
            }
        }
        //处理表格
        List<com.xiaobear.pojo.Resource> resourceList = user.getResourceList();
        //获取第一个表格
        XWPFTable table = document.getTables().get(0);
        //获取第一行
        XWPFTableRow row = table.getRow(0);
        int rowIndex = 1;
        for (com.xiaobear.pojo.Resource resource : resourceList) {
            //增加行
            addBlankRow(table,row,rowIndex);
            XWPFTableRow tableRow = table.getRow(rowIndex);
            tableRow.getCell(0).setText(resource.getName());
            tableRow.getCell(1).setText(resource.getPrice().toString());
            tableRow.getCell(2).setText(resource.getNeedReturn()?"需要":"不需要");
            File imageFile = new File(classpath,"/static"+resource.getPhoto());
            setCellImage(tableRow.getCell(3),imageFile);
            rowIndex++;
        }
        //     处理表格开始结束
        //        4、导出word
        String filename = "员工(" + user.getUserName() + ")合同.docx";
        response.setHeader("content-disposition", "attachment;filename=" + new String(filename.getBytes(), "ISO8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        document.write(response.getOutputStream());
    }


    /**
     * 向单元格中写入图片
     * @param cell
     * @param imageFile
     */
    private static void setCellImage(XWPFTableCell cell, File imageFile) {

        XWPFRun run = cell.getParagraphs().get(0).createRun();
        //        InputStream pictureData, int pictureType, String filename, int width, int height
        try(FileInputStream inputStream = new FileInputStream(imageFile)) {
            run.addPicture(inputStream,XWPFDocument.PICTURE_TYPE_JPEG,imageFile.getName(), Units.toEMU(100),Units.toEMU(50));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 增加一个空行
     * @param table
     * @param row
     * @param rowIndex
     */
    public static void addBlankRow(XWPFTable table, XWPFTableRow row, int rowIndex){
        //插入一行 ps:没有样式
        XWPFTableRow xwpfTableRow = table.insertNewTableRow(rowIndex);
        xwpfTableRow.getCtRow().setTrPr(row.getCtRow().getTrPr());
        //获取原来row的单元格
        List<XWPFTableCell> tableCells = row.getTableCells();
        if (CollectionUtils.isEmpty(tableCells)) {
        }
        XWPFTableCell temp;
        for (XWPFTableCell cell : tableCells) {
            temp = xwpfTableRow.addNewTableCell();
            //单元格的样式、属性
            temp.getCTTc().setTcPr(cell.getCTTc().getTcPr());
            temp.getParagraphs().get(0).getCTP().setPPr(cell.getParagraphs().get(0).getCTP().getPPr());
        }

    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小熊学Java

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

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

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

打赏作者

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

抵扣说明:

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

余额充值