word表格

/**
 *
 */
package org.example.controller;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.imageio.stream.FileImageInputStream;
import java.io.*;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 导出Excel公共方法
 *
 * @author lyq
 */
public class ExportWordUtil {

    private static final Logger logger = LoggerFactory.getLogger(ExportWordUtil.class);

    public static void main(String[] args) throws IOException {
        //解析html 按行存入map
        List<String> list1 = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
        list2.add("The Settlemnet:YES");
        List<String> list3 = new ArrayList<>();
        list3.add("");
        FileInputStream in = new FileInputStream("");
        byte[] ba = new byte[in.available()];
        int len = in.read(ba);
        FileInputStream in2 = new FileInputStream("");
        byte[] ba2 = new byte[in2.available()];
        int len2 = in2.read(ba2);
        List<Object> images = new ArrayList<>();
        FileInputStream in3 = new FileInputStream("");
        byte[] ba3 = new byte[in3.available()];
        int len3 = in3.read(ba3);
        FileInputStream in4 = new FileInputStream("");
        byte[] ba4 = new byte[in4.available()];
        int len4 = in4.read(ba4);
        images.add(ba);
        images.add(ba2);
        images.add(ba4);
        images.add(ba3);

        //按根据行数创建表格,下载图片转码并存入
        Map<Integer, List<String>> map = new HashMap<>();
        map.put(0, list1);
        map.put(1, list2);
        map.put(2, list3);
        String classPath = "D:\\";
        Calendar c = Calendar.getInstance();

        String fileName = "" + c.get(Calendar.YEAR)
                + c.get(Calendar.DAY_OF_MONTH) + c.get(Calendar.HOUR_OF_DAY) + c.get(Calendar.MILLISECOND) + ".docx";
        FileOutputStream fos = new FileOutputStream(classPath + fileName);
        XWPFDocument xdoc = new ExportWordUtil().createTable(map, images);
        xdoc.write(fos);
        fos.close();
    }


    public XWPFDocument createTable(Map<Integer, List<String>> map, List<Object> images) {
        CustomXWPFDocument xdoc = new CustomXWPFDocument();
        int imagerow = images.size() > 2 ? 2 : 1;
        XWPFTable table = xdoc.createTable(map.size() + imagerow, 3);
        table.removeInsideVBorder();
        String bgColor = "111111";
        CTTbl ttbl = table.getCTTbl();
        CTTblPr tblPr = ttbl.getTblPr() == null ? ttbl.addNewTblPr() : ttbl.getTblPr();
        CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW();
        tblWidth.setW(new BigInteger("8600"));
        tblWidth.setType(STTblWidth.DXA); // STTblWidth.AUTO 自动长度
        //循环行
        for (Integer k : map.keySet()) {
            //循环列
            //插入文字
            List<String> strings = map.get(k);
            for (int i = 0; i < strings.size(); i++) {
                try {
                    setCellText(xdoc, getCellHight(table, k, i, 600), strings.get(i), bgColor, 33, 11, "微软雅黑");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        //插入图片
        XWPFTableCell cellHight = getCellHight(table, 3, 0, 1200);
        XWPFTableCell cellHight2 = getCellHight(table, 3, 1, 1200);
        XWPFParagraph xwpfParagraph = cellHight.addParagraph();
        cellHight.removeParagraph(0);
        setCellPic(xdoc, xwpfParagraph, (byte[]) images.get(0));
        XWPFTableCell cellHight3 = getCellHight(table, 3, 2, 1200);
        mergeCellsHorizontal(table, 3, 0, 1);

        XWPFParagraph xwpfParagraph3 = cellHight3.addParagraph();
        cellHight3.removeParagraph(0);
        setCellPic(xdoc, xwpfParagraph3, (byte[]) images.get(1));






        return xdoc;
    }

    /**
     * 在cell 里面插入图片
     * @param xdoc
     * @param paragraph
     * @param imageByte
     */
    private void createPic(CustomXWPFDocument xdoc, XWPFParagraph paragraph, byte[] imageByte) {
        try {
            xdoc.addPictureData(imageByte, XWPFDocument.PICTURE_TYPE_JPEG);
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        }
        xdoc.createPicture(paragraph, xdoc.getAllPictures().size() - 1, 250, 200, "    ");
    }

    // 设置表格高度
    private XWPFTableCell getCellHight(XWPFTable xTable, int rowNomber, int cellNumber, int hight) {
        XWPFTableRow row = null;
        row = xTable.getRow(rowNomber);
        row.setHeight(hight);
        row.setCantSplitRow(false);
        XWPFTableCell cell = null;
        cell = row.getCell(cellNumber);
            cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
        return cell;
    }

    /**
     * 创建图片
     */
    private void setCellPic(CustomXWPFDocument xdoc, XWPFParagraph cell, byte[] imageByte) {
        createPic(xdoc, cell, imageByte);
    }

    private void setCellText(CustomXWPFDocument xDocument, XWPFTableCell cell, String text, String bgcolor, int width,
                             int fontSize, String textType) {
        setCellText(xDocument, cell, text, bgcolor, width, fontSize, textType, ParagraphAlignment.LEFT);
    }

    /**
     *
     * @param xDocument
     * @param cell
     * @param text
     * @param bgcolor
     * @param width
     */
    private void setCellText(CustomXWPFDocument xDocument, XWPFTableCell cell, String text, String bgcolor, int width,
                             int fontSize, String textType, ParagraphAlignment align) {
        setCellText(xDocument, cell, text, bgcolor, width, fontSize, textType, align, false);
    }

    private void setCellText(CustomXWPFDocument xDocument, XWPFTableCell cell, String text, String bgcolor, int width,
                             int fontSize, String textType, ParagraphAlignment align, boolean isBold) {
        CTTc cttc = cell.getCTTc();
        CTTcPr cellPr = cttc.addNewTcPr();
        cellPr.addNewTcW().setW(BigInteger.valueOf(width));
        XWPFParagraph pIO = cell.addParagraph();
        cell.setWidthType(TableWidthType.PCT);
        if (null == align) {
            pIO.setAlignment(ParagraphAlignment.LEFT);
        } else {
            pIO.setAlignment(align);
        }
        cell.removeParagraph(0);
        if (text.contains("\n")) {
           /* String[] myStrings = text.split("\n");
            for (int i = 0; i < myStrings.length; i++) {
                String temp = myStrings[i];
                if (isBold) {
                    if (i == 0) {
                        setTextStyle(pIO, textType, bgcolor, fontSize, temp, true, true);
                    } else {
                        setTextStyle(pIO, textType, bgcolor, fontSize, "      " + temp, true, false);
                    }
                } else {
                    setTextStyle(pIO, textType, bgcolor, fontSize, temp, true, false);
                }
            }*/
        } else {
            setTextStyle(pIO, textType, bgcolor, fontSize, text, false, false);
        }
    }

    private void setTextStyle(XWPFParagraph pIO, String textType, String bgcolor, int fontSize, String text,
                              boolean isEntery, boolean isBold) {
        XWPFRun rIO = pIO.createRun();


        if (textType == null || textType.equals("")) {
            rIO.setFontFamily("微软雅黑");
        } else {
            rIO.setFontFamily(textType);
        }
        if (bgcolor == null || bgcolor.equals("")) {
            rIO.setColor("000000");
        } else {
            rIO.setColor(bgcolor);
        }
        rIO.setFontSize(fontSize);
        rIO.setText(text);
        if (isBold)
            rIO.setBold(true);
       /* if (isEntery)
            rIO.addBreak();*/
    }

    // 设置表格间的空行
    public void setEmptyRow(CustomXWPFDocument xdoc, XWPFRun r1) {
        XWPFParagraph p1 = xdoc.createParagraph();
        p1.setAlignment(ParagraphAlignment.CENTER);
        p1.setVerticalAlignment(TextAlignment.CENTER);
        r1 = p1.createRun();
    }

    // word跨列合并单元格
    public void mergeCellsHorizontal(XWPFTable table, int row, int startCol, int endCol) {
        for (int cellIndex = startCol; cellIndex <= endCol; cellIndex++) {
            XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
            if (cellIndex == startCol) {
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            } else {
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    // word跨行并单元格
    public void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
        for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
            XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
            if (rowIndex == fromRow) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值