管道基础大数据平台系统开发-【后端】-Server
13693261870
2024-03-21 b9b490e0ec226389c6e2502fecf918f7537d8c57
添加Word Excel测试方法
已修改4个文件
276 ■■■■■ 文件已修改
src/main/java/com/lf/server/config/InitConfig.java 6 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/lf/server/helper/ExcelHelper.java 26 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/lf/server/helper/WordHelper.java 203 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/lf/server/service/all/TestService.java 41 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/lf/server/config/InitConfig.java
@@ -33,8 +33,8 @@
    @Resource
    Environment env;
    //@Resource
    //TestService testService;
    @Resource
    TestService testService;
    @Resource
    AutoQueryService autoQueryService;
@@ -52,7 +52,7 @@
            GdalHelper.init(env.getProperty("sys.gdal_path"));
            UploadAttachService.init(env.getProperty("sys.attachTabs"));
            //testService.testRegister();
            //testService.testExcel();
            pathHelper.init();
            StaticData.ADMIN = env.getProperty("sys.admin");
            argsService.initSettingData();
src/main/java/com/lf/server/helper/ExcelHelper.java
@@ -75,6 +75,32 @@
     * 写入Excel模板
     *
     * @param source 源文件(模板)
     * @param target  目录文件
     * @param map     键值对Map
     * @param listMap 列表Map
     */
    public static <T> void writeToTemplate(String source, String target, Map<String, Object> map, Map<String, List<T>> listMap) {
        // 根据模板写入数据,如果目标文件不存在,则自动创建文件
        ExcelWriter excelWriter = EasyExcel.write(target).withTemplate(source).build();
        // 在工作簿0中写入数据,如果模板中不存在练习工作簿,则会在目标文件中自动创建
        WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
        // 垂直写入数据,如果要水平写入,将VERTICAL替换为HORIZONTAL
        FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.VERTICAL).build();
        // 写入数据
        excelWriter.fill(map, writeSheet);
        listMap.forEach((k, v) -> excelWriter.fill(new FillWrapper(k, v), fillConfig, writeSheet));
        // 结束写入
        excelWriter.finish();
    }
    /**
     * 写入Excel模板
     *
     * @param source 源文件(模板)
     * @param target 目录文件
     * @param map    数据源
     */
src/main/java/com/lf/server/helper/WordHelper.java
@@ -8,18 +8,22 @@
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
 * Word帮助类
 *
 * @author WWW
 * @date 2024-03-21
 */
public class WordHelper {
    private final static Log log = LogFactory.getLog(WordHelper.class);
    /**
     * 通过word模板生成word的主方法
     * https://blog.csdn.net/qq_46112324/article/details/128156675
     */
    public static void generateWord(String inputFile, String outPutFile, Map<String, String> insertTextMap, List<String[]> addList) {
    public static void generateWord(String inputFile, String outPutFile, Map<String, String> textMap, List<String[]> tableList) {
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
@@ -28,18 +32,23 @@
            outputStream = new FileOutputStream(outPutFile);
            // 获取docx解析对象
            XWPFDocument xwpfDocument = new XWPFDocument(inputStream);
            XWPFDocument document = new XWPFDocument(inputStream);
            // 处理所有文段数据,除了表格
            if (null != insertTextMap && insertTextMap.size() > 0) {
                handleParagraphs(xwpfDocument, insertTextMap);
            if (null != textMap && textMap.size() > 0) {
                handleParagraphs(document, textMap);
                //changeText(document, textMap);
            }
            // 处理表格数据
            handleTable(xwpfDocument, insertTextMap, addList);
            // 解析替换表格对象
            if (null != tableList && tableList.size() > 0) {
                handleTable(document, textMap, tableList);
                //changeTable(document, textMap, tableList);
            }
            // 写入数据
            xwpfDocument.write(outputStream);
            document.write(outputStream);
            document.close();
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        } finally {
@@ -55,6 +64,170 @@
            }
        }
    }
    /**
     * 替换表格对象方法
     *
     * @param document  docx解析对象
     * @param textMap   需要替换的信息集合
     * @param tableList 需要插入的表格信息集合
     */
    public static void changeTable(XWPFDocument document, Map<String, String> textMap, List<String[]> tableList) {
        // 获取表格对象集合
        List<XWPFTable> tables = document.getTables();
        for (int i = 0; i < tables.size(); i++) {
            XWPFTable table = tables.get(i);
            if (table.getRows().size() > 1) {
                // 判断表格是需要替换还是需要插入,判断逻辑有$为替换,表格无$为插入
                if (!checkText(table.getText())) {
                    insertTable(table, tableList);
                }
            }
        }
    }
    /**
     * 替换段落文本
     *
     * @param document docx解析对象
     * @param textMap  需要替换的信息集合
     */
    public static void changeText(XWPFDocument document, Map<String, String> textMap) {
        // 获取段落集合
        List<XWPFTable> tables = document.getTables();
        for (XWPFTable table : tables) {
            if (checkText(table.getText())) {
                List<XWPFTableRow> rows = table.getRows();
                for (XWPFTableRow row : rows) {
                    List<XWPFTableCell> tableCells = row.getTableCells();
                    for (XWPFTableCell cell : tableCells) {
                        if (checkText(cell.getText())) {
                            List<XWPFParagraph> paragraphs = cell.getParagraphs();
                            for (XWPFParagraph paragraph : paragraphs) {
                                // 判断此段落时候需要进行替换
                                String text = paragraph.getText();
                                if (checkText(text)) {
                                    List<XWPFRun> runs = paragraph.getRuns();
                                    for (XWPFRun run : runs) {
                                        // 替换模板原来位置
                                        if (checkText(run.toString())) {
                                            run.setText(changeValue(paragraph.getText(), textMap), 0);
                                        } else {
                                            run.setText("", 0);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    /**
     * 判断文本中时候包含$
     *
     * @param text 文本
     * @return 包含返回true, 不包含返回false
     */
    public static boolean checkText(String text) {
        boolean check = false;
        if (text.contains("$")) {
            check = true;
        }
        return check;
    }
    /**
     * 匹配传入信息集合与模板
     *
     * @param value   模板需要替换的区域
     * @param textMap 传入信息集合
     * @return 模板需要替换区域信息集合对应值
     */
    public static String changeValue(String value, Map<String, String> textMap) {
        Set<Map.Entry<String, String>> textSets = textMap.entrySet();
        for (Map.Entry<String, String> textSet : textSets) {
            // 匹配模板与替换值 格式${key}
            String key = "${" + textSet.getKey() + "}";
            if (key.contains(value)) {
                value = textSet.getValue();
            }
        }
        return value;
    }
    /**
     * 为表格插入数据,行数不够添加新行
     *
     * @param table     需要插入数据的表格
     * @param tableList 插入数据集合
     */
    public static void insertTable(XWPFTable table, List<String[]> tableList) {
        // 记录需要插入的第一行
        int start = -1;
        for (int i = 0; i < table.getRows().size(); i++) {
            for (int j = 0; j < table.getRows().get(i).getTableCells().size(); j++) {
                if ("".equals(table.getRows().get(i).getTableCells().get(j).getText())) {
                    start = i;
                    break;
                }
            }
        }
        // 创建行,根据需要插入的数据添加新行
        if (start != -1) {
            for (int i = 1; i < tableList.size(); i++) {
                insertRow(table, start, start + i);
            }
        }
        // 遍历表格插入数据
        List<XWPFTableRow> rows = table.getRows();
        for (int i = start; i < rows.size(); i++) {
            List<XWPFTableCell> cells = rows.get(i).getTableCells();
            for (int j = 0; j < table.getRow(start).getTableCells().size(); j++) {
                XWPFTableCell cell = cells.get(j);
                cell.setText(tableList.get(0)[j]);
            }
            tableList.remove(0);
        }
    }
    /**
     * 为表格插入数据,行数不够添加新行
     *
     * @param table        需要插入数据的表格
     * @param copyRowIndex 复制行号
     * @param newRowIndex  新行号
     */
    public static void insertRow(XWPFTable table, int copyRowIndex, int newRowIndex) {
        // 在表格中指定的位置新增一行
        XWPFTableRow targetRow = table.insertNewTableRow(newRowIndex);
        // 获取需要复制行对象
        XWPFTableRow copyRow = table.getRow(copyRowIndex);
        // 复制行对象
        targetRow.getCtRow().setTrPr(copyRow.getCtRow().getTrPr());
        //或许需要复制的行的列
        List<XWPFTableCell> copyCells = copyRow.getTableCells();
        // 复制列对象
        XWPFTableCell targetCell = null;
        for (XWPFTableCell copyCell : copyCells) {
            targetCell = targetRow.addNewTableCell();
            targetCell.getCTTc().setTcPr(copyCell.getCTTc().getTcPr());
            if (copyCell.getParagraphs() != null && copyCell.getParagraphs().size() > 0) {
                targetCell.getParagraphs().get(0).getCTP().setPPr(copyCell.getParagraphs().get(0).getCTP().getPPr());
                if (copyCell.getParagraphs().get(0).getRuns() != null
                        && copyCell.getParagraphs().get(0).getRuns().size() > 0) {
                    XWPFRun cellR = targetCell.getParagraphs().get(0).createRun();
                    cellR.setBold(copyCell.getParagraphs().get(0).getRuns().get(0).isBold());
                }
            }
        }
    }
    /**
     * 处理所有文段数据,除了表格
@@ -165,8 +338,11 @@
    public static String matchesValue(String wordValue, Map<String, String> map) {
        for (String s : map.keySet()) {
            String s1 = "${" + s + "}";
            if (s1.equals(wordValue)) {
            /*if (s1.equals(wordValue)) {
                wordValue = map.get(s);
            }*/
            if (wordValue.contains(s1)) {
                wordValue = wordValue.replace(s1, map.get(s));
            }
        }
@@ -177,7 +353,7 @@
     * 测试是否包含需要替换的数据
     */
    public static boolean isReplacement(String text) {
        return text.contains("$");
        return text.contains("${");
    }
    /**
@@ -257,10 +433,8 @@
                CTRPr tmpRpr = tmpR.getCTR().getRPr();
                if (tmpRpr.isSetRFonts()) {
                    CTFonts tmpFonts = tmpRpr.getRFonts();
                    CTRPr cellRpr = cellR.getCTR().isSetRPr() ? cellR
                            .getCTR().getRPr() : cellR.getCTR().addNewRPr();
                    CTFonts cellFonts = cellRpr.isSetRFonts() ? cellRpr
                            .getRFonts() : cellRpr.addNewRFonts();
                    CTRPr cellRpr = cellR.getCTR().isSetRPr() ? cellR.getCTR().getRPr() : cellR.getCTR().addNewRPr();
                    CTFonts cellFonts = cellRpr.isSetRFonts() ? cellRpr.getRFonts() : cellRpr.addNewRFonts();
                    cellFonts.setAscii(tmpFonts.getAscii());
                    cellFonts.setAsciiTheme(tmpFonts.getAsciiTheme());
                    cellFonts.setCs(tmpFonts.getCs());
@@ -285,8 +459,7 @@
                cellSpacing.setAfter(tmpSpacing.getAfter());
            }
            if (tmpSpacing.getAfterAutospacing() != null) {
                cellSpacing.setAfterAutospacing(tmpSpacing
                        .getAfterAutospacing());
                cellSpacing.setAfterAutospacing(tmpSpacing.getAfterAutospacing());
            }
            if (tmpSpacing.getAfterLines() != null) {
                cellSpacing.setAfterLines(tmpSpacing.getAfterLines());
src/main/java/com/lf/server/service/all/TestService.java
@@ -8,6 +8,7 @@
import com.lf.server.entity.all.PermsAuthEntity;
import com.lf.server.entity.all.ResAuthEntity;
import com.lf.server.entity.bd.DlgagnpEntity;
import com.lf.server.entity.ctrl.CountEntity;
import com.lf.server.entity.data.MetaEntity;
import com.lf.server.entity.data.MetaFileEntity;
import com.lf.server.entity.md.MdzxcgEntity;
@@ -265,4 +266,44 @@
            //
        }
    }
    public void testWord() {
        String inputFile = "C:\\Users\\Administrator\\Desktop\\ts\\项目数据分类统计.docx";
        String outPutFile = "C:\\Users\\Administrator\\Desktop\\ts\\NewWord.docx";
        Map<String, String> textMap = new HashMap<>();
        textMap.put("title", "深圳液化天然气应急调峰站外输管道工程(XQ03T04)");
        List<String[]> tableList = new ArrayList<>();
        tableList.add(new String[]{"" + 1, "数字线划图", "123.54平方米"});
        tableList.add(new String[]{"" + 2, "地灾点", "120个"});
        WordHelper.generateWord(inputFile, outPutFile, textMap, tableList);
    }
    public void testExcel() {
        String source = "C:\\Users\\Administrator\\Desktop\\ts\\项目数据分类统计.xlsx";
        String target = "C:\\Users\\Administrator\\Desktop\\ts\\NewWord.xlsx";
        List<CountEntity> list = new ArrayList<>();
        CountEntity c1 = new CountEntity();
        c1.setNo(1);
        c1.setM1("数字线划图");
        c1.setM2("123.54平方米");
        list.add(c1);
        CountEntity c2 = new CountEntity();
        c2.setNo(2);
        c2.setM1("地灾点");
        c2.setM2("120个");
        list.add(c2);
        Map<String, Object> map = new HashMap<>(1);
        map.put("title", "深圳液化天然气应急调峰站外输管道工程(XQ03T04)");
        Map<String, List<CountEntity>> listMap = new HashMap<>(1);
        listMap.put("data", list);
        ExcelHelper.writeToTemplate(source, target, map, listMap);
    }
}