Browse Source

word转换测试

hym 4 years ago
parent
commit
5b138cfc01

+ 5 - 0
user_center/pom.xml

@@ -50,6 +50,11 @@
                </exclusion>
            </exclusions>
        </dependency>
+       <dependency>
+           <groupId>org.apache.poi</groupId>
+           <artifactId>poi-scratchpad</artifactId>
+           <version>4.0.1</version>
+       </dependency>
    </dependencies>
 
 </project>

+ 2 - 2
user_center/src/main/resources/mapper/UserGroupMapper.xml

@@ -219,9 +219,9 @@
         select 	<include refid="userColumns"/>,b.id userGroupId
          from uims_user a left join uims_group_user b on a.id=b.USER_ID
         <include refid="sysAreaJoins"/>
-        where  a.status!=-1  and userrole.status!=-1
+        where  a.status!=-1
         <if test="id != -1 ">
-           and  b.GROUP_ID=#{id} and b.status!=-1
+           and  b.GROUP_ID=#{id} and b.status!=-1 and userrole.status!=-1
         </if>
         <if test="id == -1 ">
           and  b.GROUP_ID is null

+ 14 - 0
user_center/src/test/com/huaxu/test/TableSource.java

@@ -0,0 +1,14 @@
+package com.huaxu.test;
+
+import lombok.Data;
+
+@Data
+public class TableSource {
+
+    private String name;
+    private String cloumnName;
+    private String type;
+    private int length;
+    private String primary;
+    private String description;
+}

+ 115 - 1
user_center/src/test/com/huaxu/test/TestOrgTree.java

@@ -11,12 +11,126 @@ import com.huaxu.model.ProgramItem;
 import org.junit.Test;
 import org.springframework.beans.BeanUtils;
 
+import java.sql.*;
 import java.util.*;
 
 import static com.google.common.collect.Lists.newArrayList;
 
 public class TestOrgTree {
-   // @Test
+    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
+    static final String DB_URL = "jdbc:mysql://114.135.61.188:33306/udip_unit?characterEncoding=utf8";
+
+    // MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
+    //static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
+    //static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
+
+
+    // 数据库的用户名与密码,需要根据自己的设置
+    static final String USER = "root";
+    static final String PASS = "100Zone@123";
+    private void produceTableByWord(String inputUrl,String outputUrl, List<String[]> testList ){
+
+
+        Map<String, String> testMap = new HashMap<String, String>();
+
+
+
+        WordUtil.changWord(inputUrl, outputUrl, testMap, testList);
+    }
+    private void produceTable(String tableName,  DatabaseMetaData dbMetaData){
+
+        try{
+            // 注册 JDBC 驱动
+            String inputUrl = "D:\\test\\2020\\10\\31\\tableModel.docx";
+            //新生产的模板文件
+            String outputUrl = "D:\\test\\2020\\10\\30\\"+tableName+".docx";
+            List<String[]> testList = new ArrayList<String[]>();
+            // 打开链接
+
+            String schemaName="udip_unit";
+            System.out.println(" 实例化表对象..."+tableName);
+            ResultSet rs = dbMetaData.getColumns(null, schemaName, tableName, "%");
+            List<TableSource>list =new ArrayList<>();
+            // 展开结果集数据库
+            while(rs.next()){
+                TableSource tableSource=new TableSource();
+                String columnName = rs.getString("COLUMN_NAME");// 列名
+                String dataTypeName = rs.getString("TYPE_NAME");// java.sql.Types类型名称
+                String comment = rs.getString("REMARKS");
+                int columnSize = rs.getInt("COLUMN_SIZE");// 列大小
+                tableSource.setCloumnName(columnName);
+                if(columnName.equals("create_date")){
+                    comment="创建时间";
+                }
+                else if(columnName.equals("create_by")){
+                    comment="创建人";
+                }
+                else if(columnName.equals("update_date")){
+                    comment="更新时间";
+
+                }
+                else if(columnName.equals("update_by")){
+                    comment="更新人";
+                }else if(columnName.equals("status")){
+                    comment="删除标识";
+                }
+                tableSource.setName(comment);
+                tableSource.setType(dataTypeName);
+                tableSource.setLength(columnSize);
+                list.add(tableSource);
+                testList.add(new String[]{tableSource.getName(),tableSource.getCloumnName()
+                        ,tableSource.getType(),tableSource.getLength()+"","",
+                        ""});
+
+            }
+            produceTableByWord(inputUrl,outputUrl,testList);
+           /* EasyExcel.write("D:\\test\\2020\\10\\31/"+tableName+".xlsx", TableSource.class)
+                    .excelType(ExcelTypeEnum.XLSX)
+                    .registerWriteHandler(new CustemhandlerUtils())
+                    .registerWriteHandler(EasyExcelUtil.getStyleStrategy())
+                    .sheet("Export")
+                    .doWrite(list);*/
+            // 完成后关闭
+            rs.close();
+
+
+        }catch(SQLException se){
+            // 处理 JDBC 错误
+            se.printStackTrace();
+        }catch(Exception e){
+            // 处理 Class.forName 错误
+            e.printStackTrace();
+        }
+    }
+    @Test
+    public void test2() throws SQLException, ClassNotFoundException {
+        Class.forName(JDBC_DRIVER);
+        Connection conn = null;
+
+        conn = DriverManager.getConnection(DB_URL,USER,PASS);
+        DatabaseMetaData dbMetaData = conn.getMetaData();
+        System.out.println("连接数据库...");
+
+
+        // 执行查询
+
+        /*String []tables={"SC_ROLE","SC_USER_ROLE","SC_PERMISSION","SC_ROLE_PERMISSION","SC_ROLE_PERMISSION","SC_ROLE_PERMISSION"
+        ,"SC_SITE","SC_SITE_PERMISSION","SC_SITE_USER","SC_LOGIN_LOG","SC_BUILDING","SC_COMMUNITY"
+        ,"SC_AREA","SC_MESSAGE","SC_DEVICE","SC_DEVICE_DATA_DIM","SC_METER_READ_RECORD","SC_SITE_PERMISSION","SC_SITE_PERMISSION",
+                "SC_SITE_PERMISSION","SC_SITE_PERMISSION","SC_SITE_PERMISSION",
+                "sc_stat_meter_read_rate_by_building","sc_stat_meter_read_rate_by_building_15day",
+        "sc_stat_meter_read_rate_by_building_month","sc_clearing_plan", "sc_clearing_record_item"};*/
+        String []tables={"udip_unit_profile_t","udip_unit_attribute_t","udip_unit_specs_t"
+        ,"udip_unit_method_t","udip_unit_param_t","udip_unit_t","udip_unit_data_t",
+                "udip_unit_command_t"};
+
+        for (int i = 0; i < tables.length; i++) {
+         produceTable(tables[i],dbMetaData);
+        }
+
+        conn.close();
+    }
+    // @Test
     public void test(){
       /*  List<TestEXCEL>list =new ArrayList<>();
         for(int i=0;i<1000000;i++){

+ 197 - 0
user_center/src/test/com/huaxu/test/WordUtil.java

@@ -0,0 +1,197 @@
+package com.huaxu.test;
+
+import org.apache.poi.POIXMLDocument;
+import org.apache.poi.xwpf.usermodel.*;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class WordUtil {
+    /**
+     * 根据模板生成新word文档
+     * 判断表格是需要替换还是需要插入,判断逻辑有$为替换,表格无$为插入
+     * @param inputUrl 模板存放地址
+     * @param
+     * @param textMap 需要替换的信息集合
+     * @param tableList 需要插入的表格信息集合
+     * @return 成功返回true,失败返回false
+     */
+    public static boolean changWord(String inputUrl, String outputUrl,
+                                    Map<String, String> textMap, List<String[]> tableList) {
+
+        //模板转换默认成功
+        boolean changeFlag = true;
+        try {
+            //获取docx解析对象
+            XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(inputUrl));
+            //解析替换文本段落对象
+            changeText(document, textMap);
+            //解析替换表格对象
+           changeTable(document, textMap, tableList);
+
+            //生成新的word
+            File file = new File(outputUrl);
+            FileOutputStream stream = new FileOutputStream(file);
+            document.write(stream);
+            stream.close();
+
+        } catch (IOException e) {
+            e.printStackTrace();
+            changeFlag = false;
+        }
+
+        return changeFlag;
+
+    }
+
+    /**
+     * 替换段落文本
+     * @param document docx解析对象
+     * @param textMap 需要替换的信息集合
+     */
+    public static void changeText(XWPFDocument document, Map<String, String> textMap){
+        //获取段落集合
+        List<XWPFParagraph> paragraphs = document.getParagraphs();
+
+        for (XWPFParagraph paragraph : paragraphs) {
+            //判断此段落时候需要进行替换
+            String text = paragraph.getText();
+            if(checkText(text)){
+                List<XWPFRun> runs = paragraph.getRuns();
+                for (XWPFRun run : runs) {
+                    //替换模板原来位置
+                    run.setText(changeValue(run.toString(), textMap),0);
+                }
+            }
+        }
+
+    }
+
+    /**
+     * 替换表格对象方法
+     * @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++) {
+            //只处理行数大于等于2的表格,且不循环表头
+            XWPFTable table = tables.get(i);
+            if(table.getRows().size()>1){
+                //判断表格是需要替换还是需要插入,判断逻辑有$为替换,表格无$为插入
+                if(checkText(table.getText())){
+                    List<XWPFTableRow> rows = table.getRows();
+                    //遍历表格,并替换模板
+                    eachTable(rows, textMap);
+                }else{
+//                  System.out.println("插入"+table.getText());
+                    insertTable(table, tableList);
+                }
+            }
+        }
+    }
+
+
+
+
+
+    /**
+     * 遍历表格
+     * @param rows 表格行对象
+     * @param textMap 需要替换的信息集合
+     */
+    public static void eachTable(List<XWPFTableRow> rows ,Map<String, String> textMap){
+        for (XWPFTableRow row : rows) {
+            List<XWPFTableCell> cells = row.getTableCells();
+            for (XWPFTableCell cell : cells) {
+                //判断单元格是否需要替换
+                if(checkText(cell.getText())){
+                    List<XWPFParagraph> paragraphs = cell.getParagraphs();
+                    for (XWPFParagraph paragraph : paragraphs) {
+                        List<XWPFRun> runs = paragraph.getRuns();
+                        for (XWPFRun run : runs) {
+                            run.setText(changeValue(run.toString(), textMap),0);
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    /**
+     * 为表格插入数据,行数不够添加新行
+     * @param table 需要插入数据的表格
+     * @param tableList 插入数据集合
+     */
+    public static void insertTable(XWPFTable table, List<String[]> tableList){
+        //创建行,根据需要插入的数据添加新行,不处理表头
+        for(int i = 1; i < tableList.size(); i++){
+            XWPFTableRow row =table.createRow();
+        }
+        //遍历表格插入数据
+        List<XWPFTableRow> rows = table.getRows();
+        for(int i = 2; i < rows.size(); i++){
+            XWPFTableRow newRow = table.getRow(i);
+            newRow.addNewTableCell();
+            newRow.addNewTableCell();
+            List<XWPFTableCell> cells = newRow.getTableCells();
+            for(int j = 0; j < cells.size(); j++){
+                XWPFTableCell cell = cells.get(j);
+                int index=i-2;
+                 cell.setText(tableList.get(index)[j]);
+
+
+            }
+        }
+
+    }
+
+
+
+    /**
+     * 判断文本中时候包含$
+     * @param text 文本
+     * @return 包含返回true,不包含返回false
+     */
+    public static boolean checkText(String text){
+        boolean check  =  false;
+        if(text.indexOf("$")!= -1){
+            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(value.indexOf(key)!= -1){
+                value = textSet.getValue();
+            }
+        }
+        //模板未匹配到区域替换为空
+        if(checkText(value)){
+            value = "";
+        }
+        return value;
+    }
+
+
+
+
+}