Export all libraries and field comments and related information of the MySQL database as a word document - tools

Next, I will introduce a self-implemented tool class to connect to MySQL or Oracle data, and use the written tool class to export the information of all libraries and tables in the database into a word document.
The generated document is as shown in the figure:
insert image description here

1. Preparation

Create a new SpringBoot project, prepare the template of the database summary table and the templates of each sub-table, and create this template by yourself according to the reference I provided in the figure below. The template style is as follows:
summary table template
Summary Table
sub-table template
insert image description here

Two, write properties file

Fill in the following attributes according to your actual situation

#Oracle的数据库连接参数(使用oracle数据库时,请注释掉10~14行,并打开2~6行)
#sqlLx = oracle
#driver = oracle.jdbc.driver.OracleDriver
#url = jdbc:Oracle:thin:@127.0.0.1:1521:ORCL
#user = root
#pwd = 123456

#mysql的数据库连接参数(使用mysql数据库时,请注释掉2~6行,并打开10~14行)
#lib中的mysql连接jar包的版本号为6及以上(mysql-connector-java-6.0.4.jar)d的话需要加cj,把11行改为  driver = com.mysql.cj.jdbc.Driver
sqlLx = mysql
driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/数据库名称?autoReconnect=true&useUnicode=true&characterEncoding=utf8&useSSL=false
user = root
pwd = 123456

#配置数据库名称前缀
#tableName = acc_
tableName = 数据库名称

#配置数据库表字段详情表的存放地址(输出每个表格的字段详情word文档的地址,需配置)
target = 生成存放位置,如D://template/db/

Three, the main startup class

Create a new JdbcTest startup class with the following code:

public class JdbcTest {
    
    

    /**
     * @Desc 方法入口
     * @Desc 配置好sql.properties文件后,直接运行main方法即可完成生成。
     */
    public static void main(String[] args) throws Exception {
    
    
        //生成表格名称列表和表格功能列表,保存于"tb_mb.docx"路径下的文件中,并对每个表生成数据库表格详情列表,储存到target文件夹中
        exportTable();
    }

    private static String driver = null;
    private static String url = null;
    private static String user = null;
    private static String pwd = null;
	private static Connection conn = null;
    private static String target = null;
    //修改两个模板文件的位置,需修改下面的路径。 建议放在同级目录。
    private static String word_mb = "./src/com/db/table/m.docx";
    private static String tb_mb = "./src/com/db/table/tb_mb.docx";
    private static String tableName = null;
    private static String sqlLx = null;
    private static String curentTime="";

    static {
    
    
        //获取当前时间加到文件名上
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        curentTime = simpleDateFormat.format(date);
	    //获取配置文件中相应的参数,并利用参数获取数据库连接
        Properties property = new Properties();
        try {
    
    
            //修改配置文件(sql.properties)的位置,需修改下面的路径。
            property.load(new FileInputStream("./src/com/db/table/sql.properties"));
            sqlLx = property.getProperty("sqlLx");
            driver = property.getProperty("driver");
            url = property.getProperty("url");
            user = property.getProperty("user");
            pwd = property.getProperty("pwd");
            //每次生成都产生一个新的文件夹,名称加当前时间
            String tempDir = property.getProperty("target");
            if (tempDir==null||tempDir.length()==0){
    
    
                tempDir="C:\\";
            }
            target = ""+tempDir+"生成时间"+curentTime+"//";
            tableName = property.getProperty("tableName");
            if (StringUtil.isNullOrEmpty(driver)||StringUtil.isNullOrEmpty(url)||StringUtil.isNullOrEmpty(user)||StringUtil.isNullOrEmpty(pwd)){
    
    
                System.out.println("数据库连接参数非法。");
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
            System.out.println("获取配置文件失败。");
        }
	    //连接数据库
		try {
    
    
			Class.forName(driver);
			conn = DriverManager.getConnection(url,user,pwd);
		} catch (Exception e) {
    
    
			System.out.println("数据库连接异常");
			e.printStackTrace();
		}
	}

    //根据数据库表名称模糊查找表名和表注释
    private static void exportTable() throws Exception{
    
    
        List<Model> list = getTableComment(tableName,conn);
        if(list!=null&&list.size()>0){
    
    
            System.out.println("一共查到"+list.size()+"个表格。");
            fillDocxByTable(list);
            System.out.println("填充表名和表注释到doc文档成功。");
        }
        exportField(list);
        disConnect();
    }

    //从mysql的information_schema数据库中查询数据库的表格名称和注释
    public static List<Model> getTableComment(String table,Connection conn){
    
    
        List<Model> list = new ArrayList<Model>();
        if ("mysql".equalsIgnoreCase(sqlLx)){
    
    
            list = GetMysqlComment.getComment(table, conn);
        }else if ("oracle".equalsIgnoreCase(sqlLx)){
    
    
            list = GetOracleComment.getComment(table, conn);
        }
        return list;
    }

    //填充表名和表注释到doc文档中
    public static void fillDocxByTable(List<Model> list){
    
    
        Map<String, Object> params = new HashMap<String, Object>();
        File path = new File(target);
        if(!path.exists()) path.mkdirs();
        String fileName = target+"000数据库汇总表.docx";
	    if (WordUtils.replaceWord(tb_mb, fileName, params)){
    
    
            int rowIndex = 1;// 表头1行,内容从第二行开始填充
            if (insertDocxRow(fileName, 0, list.size()-1, rowIndex)) {
    
    
                // 填充表名和表注释到doc文档中
                fillDocxTbData(fileName, list, rowIndex-1);
            }
        }

    }

    //填充序号、表名、表格功能到doc文档中
    private static boolean fillDocxTbData(String target, List<Model> list, Integer rowIndex) {
    
    
        XWPFDocument document = null;
        FileOutputStream fos = null;
        XWPFTable table = null;
        Iterator<XWPFTable> itTable = null;
        try {
    
    
            document = new XWPFDocument(new FileInputStream(target));
            fos = new FileOutputStream(target);
            itTable = document.getTablesIterator();
            table = (XWPFTable) itTable.next();
            int i = 1;
            XWPFTableRow temp = null;
            if (list != null && list.size() > 0) {
    
    
                for (Model tb : list) {
    
    
                    temp = table.getRow(rowIndex + i);
                    clearData(temp, 3);// 将temp中数据填充到3列中
                    temp.getCell(0).setText(String.valueOf(i));
                    temp.getCell(1).setText(tb.getTableName());
                    temp.getCell(2).setText(tb.getDesc());
                    i++;
                }
            }
            document.write(fos);
        } catch (Exception e1) {
    
    
            e1.printStackTrace();
        } finally {
    
    
            try {
    
    
                if (fos != null)
                    fos.close();
                if (document != null)
                    document.close();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
        return true;
    }

    //根据表名模糊查询,获取字段详细信息
    private static void exportField(List<Model> list) throws Exception{
    
    
        System.out.println("数据库中一共有"+list.size()+"个表格,将查找每个表格的详细信息并生成对应word文档。");
        if(list!=null&&list.size()>0){
    
    
            int docCount=1;
            if ("mysql".equalsIgnoreCase(sqlLx)){
    
    
                for (Model model : list) {
    
    
                    //model中有两个参数,getTableName()可获取字母表名,getDesc()可获取功能说明(eg:"重点国家表(系统默认&用户自定义)")
                    List<TableDef> defList = GetMysqlComment.getTableDef(model.getTableName(), conn);
                    model.setDefList(defList);
                    fillDocx(model);
                    System.out.println("生成了第"+docCount+"个文档,名称是"+model.getTableName());
                    docCount++;
                }
            }else if ("oracle".equalsIgnoreCase(sqlLx)){
    
    
                for (Model model : list) {
    
    
                    //model中有两个参数,getTableName()可获取字母表名,getDesc()可获取功能说明(eg:"重点国家表(系统默认&用户自定义)")
                    List<TableDef> defList = GetOracleComment.getTableDef(model.getTableName(), conn);
                    model.setDefList(defList);
                    fillDocx(model);
                    System.out.println("生成了第"+docCount+"个文档,名称是"+model.getTableName());
                    docCount++;
                }
            }
            System.out.println("所有的数据库表格详情文档生成完毕,程序运行结束。");
            System.out.println("请在 "+target+" 文件夹中查看生成的文件。");
        }
        disConnect();
    }

	//在word文档中添加对应行数的空白表格行
	private static boolean insertDocxRow(String target, Integer tableIndex, Integer rowNum, Integer rowIndex) {
    
    
        XWPFDocument document = null;
        FileOutputStream fos = null;
        XWPFTable table = null;
        Iterator<XWPFTable> itTable = null;
        if (tableIndex == null)
            tableIndex = 0;
        try {
    
    
            document = new XWPFDocument(new FileInputStream(target));
            fos = new FileOutputStream(target);
            itTable = document.getTablesIterator();
            int index = 0;
            while (itTable.hasNext()) {
    
    
                table = (XWPFTable) itTable.next();
                if (tableIndex.intValue() == index)
                    break;
                index++;
            }
            XWPFTableRow row = table.getRow(rowIndex);
            for (int i = 1; i <= rowNum; i++) {
    
    
                table.addRow(row, rowIndex);
            }
            document.write(fos);
        } catch (Exception e1) {
    
    
            e1.printStackTrace();
            return false;
        } finally {
    
    
            try {
    
    
                if (fos != null)
                    fos.close();
                if (document != null)
                    document.close();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
        return true;
    }
	
	//把各个表的具体信息填充到word文档中
	public static void fillDocx(Model model){
    
    
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("tableName", model.getTableName());
        params.put("desc", model.getDesc());
        File path = new File(target);
        if(!path.exists()) path.mkdirs();
        //生成文件名,把当前时间加到文件名上
        String fileName=target+model.getTableName()+".docx";
        if (WordUtils.replaceWord(word_mb, fileName, params)) {
    
    
        	 int rowIndex = 4;// 表头4行,内容从第5行开始填充
        	 if (insertDocxRow(fileName, 0, model.getDefList().size()-1, rowIndex)) {
    
    
                 // 把各个表的具体信息填充到word文档中,失败就输出提示一下。
                 boolean IsSuccess = fillDocxData(fileName, model.getDefList(), rowIndex - 1);
                 if (!IsSuccess){
    
    
                     System.out.println(model.getTableName()+"生成失败。");
                 }
             }
        }
	}
	
    //把各个表的具体信息填充到word文档中,返回true
	private static boolean fillDocxData(String target, List<TableDef> list, Integer rowIndex) {
    
    
        XWPFDocument document = null;
        FileOutputStream fos = null;
        XWPFTable table = null;
        Iterator<XWPFTable> itTable = null;
        try {
    
    
            document = new XWPFDocument(new FileInputStream(target));
            fos = new FileOutputStream(target);
            itTable = document.getTablesIterator();
            table = (XWPFTable) itTable.next();
            int i = 1;
            XWPFTableRow temp = null;
            if (list != null && list.size() > 0) {
    
    
                for (TableDef def : list) {
    
    
                    temp = table.getRow(rowIndex + i);
                    // 每个字段有8个属性,分别是序号、标识、字段类型、名称、描述、约束条件、关联表、是否主键
                    clearData(temp, 8);
                    temp.getCell(0).setText(String.valueOf(i));
                    temp.getCell(1).setText(def.getBs());
                    temp.getCell(2).setText(def.getLx());
                    temp.getCell(3).setText(def.getMc());
                    temp.getCell(4).setText(def.getMs());
                    temp.getCell(5).setText(def.getYstj());
                    temp.getCell(6).setText(def.getGlb());
                    temp.getCell(7).setText(def.getZj().equals("1")?"√":"");
                    i++;
                }
            }
            document.write(fos);
        } catch (Exception e1) {
    
    
            e1.printStackTrace();
        } finally {
    
    
            try {
    
    
                if (fos != null)
                    fos.close();
                if (document != null)
                    document.close();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
        return true;
    }

    // 遍历获取数据
    private static void clearData(XWPFTableRow row, Integer cols) {
    
    
        for (int col = 0; col < cols; col++) {
    
    
            if (row.getCell(col).getParagraphs().size() > 0) {
    
    
                List<XWPFParagraph> plist = row.getCell(col).getParagraphs();
                for (XWPFParagraph xwpfParagraph : plist) {
    
    
                    List<XWPFRun> runs = xwpfParagraph.getRuns();
                    if (runs != null && runs.size() > 0) {
    
    
                        for (int j = 0; j < runs.size(); j++) {
    
    
                            xwpfParagraph.removeRun(j);
                        }
                    }
                }
            }
        }
    }

    //断开数据库连接
    public static void disConnect(){
    
    
        try {
    
    
            if(conn!=null) conn.close();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }
}

Form Entity Class

public class Model implements Serializable {
    
    
	/**
	 * 表格实体类
	 */
	private static final long serialVersionUID = 1L;
	private String tableName;// 表格名称
	private String desc;// 表格功能说明
	private String yt;// 表格用途;
	private List<TableDef> defList;// 表格字段定义

	public String getTableName() {
    
    
		return tableName;
	}

	public void setTableName(String tableName) {
    
    
		this.tableName = tableName;
	}

	public String getDesc() {
    
    
		return desc;
	}

	public void setDesc(String desc) {
    
    
		this.desc = desc;
	}

	public String getYt() {
    
    
		return yt;
	}

	public void setYt(String yt) {
    
    
		this.yt = yt;
	}

	public List<TableDef> getDefList() {
    
    
		return defList;
	}

	public void setDefList(List<TableDef> defList) {
    
    
		this.defList = defList;
	}
}

Annotate Entity Classes

public class Comment implements Serializable {
    
    

	/**
	 * Oracle数据库字段标识和注释实体类
	 */
	private static final long serialVersionUID = 1L;
	private String bs;// 标识
	private String comment;// 注释

	// 此处省去setter和getter方法,自行补全!
}

Form details

//表格详情信息
public class TableDef implements Serializable {
    
    

	/**
	 * 根据表名查找column表,找出每个字段的含义
	 */
	private static final long serialVersionUID = 1L;
	private String xh;// 序号
	private String bs;// 标识
	private String lx;// 字段类型
	private String mc;// 名称
	private String ms;// 描述
	private String ystj;// 约束条件
	private String glb;// 关联表
	private String zj;// 主键1:是0:否

	// 此处省去setter和getter方法,自行补全!
}

Get all table and comment information of MySQL database

public class GetMysqlComment {
    
    
    public static List<Model> getComment(String table, Connection conn) {
    
    
        List<Model> list = new ArrayList<Model>();
        StringBuffer sql = new StringBuffer("select t.TABLE_NAME,t.TABLE_COMMENT from information_schema.tables t where t.TABLE_TYPE = 'BASE TABLE' and TABLE_schema = '"+table+"' ");
        /*if(!StringUtil.isNullOrEmpty(table)){
            sql.append(" and t.TABLE_NAME like '%"+table+"%'");
        }*/
        try {
    
    
            PreparedStatement statement = conn.prepareStatement(sql.toString());
            ResultSet tbSet = statement.executeQuery();
            while (tbSet.next())
            {
    
    
                Model en = new Model();
                en.setTableName(tbSet.getString("TABLE_NAME"));
                en.setDesc(tbSet.getString("TABLE_COMMENT"));
                list.add(en);
            }
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return list;
    }

    //查找每个表格的详细信息并封装到List<TableDef>中返回
    public static List<TableDef> getTableDef(String tableName,Connection conn) throws Exception {
    
    
        //此处查询语句也需要修改
        // select b.ordinal_position,b.COLUMN_name,b.COLUMN_type,b.COLUMN_comment,b.is_nullable,b.column_key from information_schema.TABLES a LEFT JOIN information_schema.COLUMNS b ON a.table_name = b.TABLE_NAME WHERE a.table_schema = '"+tableName+"' "
        // select t.ordinal_position,t.COLUMN_name,t.COLUMN_type,t.COLUMN_comment,t.is_nullable,t.column_key from COLUMNS t WHERE TABLE_schema='gqks' and TABLE_name= '"+tableName+"' "
        // select a.ordinal_position,a.COLUMN_name,a.COLUMN_type,a.COLumn_comment,a.is_nullable,a.column_key from information_schema.COLUMNS a WHERE TABLE_schema='sy-zhhg' and TABLE_name='"+tableName+"'
        PreparedStatement ps = conn.prepareStatement("select a.ordinal_position,a.COLUMN_name,a.COLUMN_type,a.COLumn_comment,a.is_nullable,a.column_key from information_schema.COLUMNS a WHERE TABLE_schema='数据库名' and TABLE_name= '"+tableName+"' ");
        ResultSet rs = ps.executeQuery();
        ResultSetMetaData rsme = rs.getMetaData();
        List<TableDef> list = new ArrayList<TableDef>();
        /*************************遍历结果集元数据获取字段详情数据*****************************/
        while (rs.next())
        {
    
    
            TableDef def = new TableDef();
            def.setXh(rs.getString(rsme.getColumnLabel(1)));
            def.setBs(rs.getString(rsme.getColumnLabel(2)));
            def.setLx(rs.getString(rsme.getColumnLabel(3)));
            //字段描述,部分地段是 主题设置(系统内置主题,不可更改) 这样的,因此需要做一下分割
            String fieldDesc = rs.getString(rsme.getColumnLabel(4));

            //先把中文括号转换为英文括号
            if (fieldDesc.contains("(")&& fieldDesc.contains(")")){
    
    
                fieldDesc = fieldDesc.replaceAll("(", "(").replaceAll(")", ")");
            }

            if(!StringUtil.isNullOrEmpty(fieldDesc)){
    
    
                //对英文的符号进行处理,如果ms为空,再处理一次中文符号
                int s=fieldDesc.indexOf("("),d=fieldDesc.indexOf(")");
                if(s!=-1&&d!=-1){
    
    
                    String fieldMc = fieldDesc.substring(0, s);
                    String fieldMs = fieldDesc.substring(s + 1, d);
                    def.setMc(fieldMc);
                    def.setMs(fieldMs);
                }else{
    
    
                    def.setMc(fieldDesc);
                }
            }
            def.setYstj(rs.getString(rsme.getColumnLabel(5)).equalsIgnoreCase("NO")?"NOT NULL":"");
            def.setGlb("");
            def.setZj(rs.getString(rsme.getColumnLabel(6)).equalsIgnoreCase("PRI")?"1":"0");
            list.add(def);
        }
        return list;
    }
}

Obtain all table and comment information of the Oracle database

public class GetOracleComment {
    
    
    public static List<Model> getComment(String table, Connection conn) {
    
    
        //连接Oracle数据库获取数据库的表名和表注释
        table = table.toUpperCase();
        List<Model> list = new ArrayList<Model>();
        StringBuffer sql = new StringBuffer("select  t.TABLE_NAME, t.COMMENTS  from user_tab_comments t  where t.TABLE_TYPE = 'TABLE' ");
        if(!StringUtil.isNullOrEmpty(table)){
    
    
            sql.append(" and t.TABLE_NAME like '%"+table+"%'");
        }
        try {
    
    
            PreparedStatement statement = conn.prepareStatement(sql.toString());
            ResultSet tbSet = statement.executeQuery();
            while (tbSet.next())
            {
    
    
                Model en = new Model();
                en.setTableName(tbSet.getString("TABLE_NAME"));
                en.setDesc(tbSet.getString("COMMENTS"));
                list.add(en);
            }
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return list;
    }

    public static List<TableDef> getTableDef(String tableName, Connection conn) throws Exception {
    
    
        //从user_cons_columns中查字段id,字段名称,字段数据类型,字段是否非空
        PreparedStatement ps1 = conn.prepareStatement("select column_id,column_name,data_type,nullable,data_length from user_tab_columns where table_name = '"+tableName+"'");
        //从user_cons_columns中查约束类型为P的字段名称(即主键)
        PreparedStatement ps2 = conn.prepareStatement("select COLUMN_name from user_cons_columns where table_name = '"+tableName+"' and constraint_name = (select constraint_name from user_constraints where Table_Name='"+tableName+"' and constraint_type ='P')");
        ResultSet resultSet1 = ps1.executeQuery();
        ResultSet resultSet2 = ps2.executeQuery();
        String primaryKeyColumnName="";
        while (resultSet2.next()){
    
    
            primaryKeyColumnName = resultSet2.getString("COLUMN_NAME");
        }
        ResultSetMetaData rsme1 = resultSet1.getMetaData();
        List<TableDef> list = new ArrayList<TableDef>();
        /*******************设置表格详细内容*********************/
        while (resultSet1.next()){
    
    
            TableDef def = new TableDef();
            def.setXh(resultSet1.getString(rsme1.getColumnLabel(1)));
            def.setBs(resultSet1.getString(rsme1.getColumnLabel(2)));
            //字段类型此处须作拼接
            String LxPrefix = resultSet1.getString(rsme1.getColumnLabel(3));
            String LxPostfix = resultSet1.getString(rsme1.getColumnLabel(5));
            //如果是NVARCHAR类型,需要对长度进行除以2处理
            if ("NVARCHAR2".equalsIgnoreCase(LxPrefix)){
    
    
                int realLength = Integer.valueOf(LxPostfix) / 2;
                LxPostfix = String.valueOf(realLength);
            }
            StringBuffer Lx = new StringBuffer();
            Lx.append(LxPrefix).append("(").append(LxPostfix).append(")");
            def.setLx(Lx.toString());

            def.setYstj(resultSet1.getString(rsme1.getColumnLabel(4)).equalsIgnoreCase("N")?"NOT NULL":"");
            def.setGlb("");
            def.setZj(def.getBs().equalsIgnoreCase(primaryKeyColumnName)?"1":"0");
            list.add(def);
        }
        /*************************设置字段名称和字段描述*************************/
        List<Comment> comList = getFieldComment(tableName,conn);
        if(list!=null&&list.size()>0&&comList!=null&&comList.size()>0){
    
    
            for (TableDef def : list) {
    
    
                for (Comment com : comList) {
    
    
                    if(def.getBs().equals(com.getBs())){
    
    
                        String tmp = com.getComment();
                        if(!StringUtil.isNullOrEmpty(tmp)){
    
    

                            //先把中文括号转换为英文括号
                            if (tmp.contains("(")&& tmp.contains(")")){
    
    
                                tmp = tmp.replaceAll("(", "(").replaceAll(")", ")");
                            }
                            //再把字符串切割成两个,分别设置为名称和描述
                            int s=tmp.indexOf("("),d=tmp.indexOf(")");
                            if(s!=-1&&d!=-1){
    
    
                                def.setMc(tmp.substring(0, s));
                                def.setMs(tmp.substring(s+1, d));
                            }else{
    
    
                                def.setMc(tmp);
                            }
                        }
                        break;
                    }
                }
            }
        }
        return list;
    }

    //根据表格名称,获取字段详情
    public static List<Comment> getFieldComment(String tableName,Connection conn){
    
    
        List<Comment> list = new ArrayList<Comment>();
        String sql = StringUtil.format("SELECT COLUMN_NAME, COMMENTS FROM user_col_comments WHERE TABLE_NAME = '{0}'", new String[] {
    
     tableName });
        try {
    
    
            PreparedStatement statement = conn.prepareStatement(sql);
            ResultSet remarkSet = statement.executeQuery();
            while (remarkSet.next())
            {
    
    
                String colName = remarkSet.getString("COLUMN_NAME");
                String remark = remarkSet.getString("COMMENTS");
                Comment en = new Comment();
                en.setBs(colName);
                en.setComment(remark);
                list.add(en);
            }
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return list;
    }
}

WordUtils tool class

package com.db.table;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.crypt.HashAlgorithm;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

/**
 * word工具
 * @author Administrator
 *
 */
public class WordUtils {
    
    
	
	/**
	 * word模板替换
	 * @param templatePath
	 * @param outPath
	 * @param map
	 * @return
	 */
	public static boolean replaceWord(String templatePath, String outPath, Map<String, Object> map){
    
    
		String t1 = getFileType(templatePath);
		String t2 = getFileType(outPath);
		//创建目录
		File file = new File(outPath);
		File pfile= new File(file.getParentFile().getPath());
		if(!pfile.exists()) pfile.mkdirs();
		//根据文档类型替换模板内容
		if(t1.equalsIgnoreCase("doc")&&t2.equalsIgnoreCase("doc")){
    
    
			return replacedoc(templatePath,outPath,map);
		}else if(t1.equalsIgnoreCase("docx")&&t2.equalsIgnoreCase("docx")){
    
    
			return replacedocx(templatePath,outPath,map);
		}else{
    
    
			return false;
		}	
	}
	
    /**
     * doc
     * @param templateFile
     * @param outFile
     * @param map
     * @return
     */
    private static boolean replacedoc(String templateFile, String outFile, Map<String, Object> map) {
    
      
        FileOutputStream fos = null;  
        try {
    
      
        	HWPFDocument document = new HWPFDocument(new FileInputStream(templateFile));  
            Range range = document.getRange();  
            for (Map.Entry<String, Object> entry : map.entrySet()) {
    
      
                range.replaceText(entry.getKey(), entry.getValue()==null?"":entry.getValue().toString());  
            }  
            fos = new FileOutputStream(outFile);  
            document.write(fos);
            return true;  
        } catch (Exception e) {
    
      
            e.printStackTrace();  
            return false;  
        } finally{
    
    
        	if(fos!=null){
    
    
        		try {
    
    
        			fos.close();
				} catch (IOException e) {
    
    
					e.printStackTrace();
				}
        	}
        }    
    }
    
    /**
     * docx
     * @param templatePath
     * @param destPath
     * @param map
     * @return
     */
    private static boolean replacedocx(String templatePath, String outPath, Map<String, Object> map) {
    
      
    	FileOutputStream fos = null;
    	XWPFDocument document = null;
        try {
    
      
			//XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(templatePath));
			document = new XWPFDocument(new FileInputStream(templatePath));
            // 替换段落中的指定文字
            List<XWPFParagraph> paraList = document.getParagraphs();  
            processParagraphs(paraList,map,document); 
  
            // 替换表格中的指定文字  
            Iterator<XWPFTable> itTable = document.getTablesIterator();  
            while (itTable.hasNext()) {
    
    
                XWPFTable table = (XWPFTable) itTable.next();  
                int rcount = table.getNumberOfRows();  
                for (int i = 0; i < rcount; i++) {
    
      
                    XWPFTableRow row = table.getRow(i);  
                    List<XWPFTableCell> cells = row.getTableCells();  
                    for (XWPFTableCell cell : cells) {
    
      
                        paraList= cell.getParagraphs(); 
                        processParagraphs(paraList,map,document); 
                    }  
                }  
            }  
            fos = new FileOutputStream(outPath);
            document.enforceReadonlyProtection("83849888", HashAlgorithm.md5);
            document.write(fos);  
            return true;  
        } catch (Exception e) {
    
      
            e.printStackTrace();  
            return false;  
        }finally{
    
    
    		try {
    
    
    			if(fos!=null) fos.close();
    			if(document!=null) document.close();
			} catch (IOException e) {
    
    
				e.printStackTrace();
			}
        }     
    }
    
    //处理段落的替�?
    public static void processParagraphs(List<XWPFParagraph> paraList,Map<String, Object> param,XWPFDocument doc){
    
      
       if(paraList!=null&&paraList.size()>0){
    
    
           for (XWPFParagraph para : paraList) {
    
      
               XWPFParagraph paragraph = (XWPFParagraph) para;  
               List<XWPFRun> runs = paragraph.getRuns();  
               for (int j = 0; j < runs.size(); j++) {
    
    
            	   boolean bReplace = false;
                   String oneparaString = runs.get(j).getText(runs.get(j).getTextPosition());  
                   for (Map.Entry<String, Object> entry : param.entrySet()) {
    
     
	                   	if(!StringUtil.isNullOrEmpty(oneparaString)){
    
    
	                   		if(oneparaString.indexOf(entry.getKey())!=-1){
    
    //如果包括替换文本
	                   			bReplace = true;
		                   		Object value = entry.getValue();
		                   		if(value==null){
    
    
		                   			oneparaString = oneparaString.replace(entry.getKey(), "");
		                   		}else if(value instanceof String){
    
    
		                   			oneparaString = oneparaString.replace(entry.getKey(), entry.getValue().toString());
		                   		}else if(value instanceof Map){
    
    
		                   			//图片处理
		                   			oneparaString = oneparaString.replace(entry.getKey(), "");  
                                    @SuppressWarnings("unchecked")
									Map<String,Object> pic = (Map<String,Object>)value;  
                                    Integer width = Integer.parseInt(pic.get("width").toString());  
                                    Integer height = Integer.parseInt(pic.get("height").toString());  
                                    int picType = getPictureType(pic.get("type").toString());  
                                    byte[] byteArray = (byte[]) pic.get("content");
                                    if(byteArray!=null&&byteArray.length>0){
    
    
	                                    ByteArrayInputStream pictureData = null;
			                   			try {
    
    
			                   				bReplace = false;
			                   				runs.get(j).setText("", 0);
			                   				pictureData = new ByteArrayInputStream(byteArray); 
			                   				runs.get(j).addPicture(pictureData, picType, "", Units.toEMU(width), Units.toEMU(height));
										} catch (Exception e) {
    
    
											e.printStackTrace();
										}finally{
    
    
											try {
    
    
												if(pictureData!=null) pictureData.close();
											} catch (IOException e) {
    
    
												e.printStackTrace();
											}
										}
                                    }
		                   		}
		                   		break;
	                   		}
	                   	}
                   }
                   if(bReplace) runs.get(j).setText(oneparaString, 0);; 
          	 }
           } 
       }
    }
    
    /** 
     * 根据图片类型,取得对应的图片类型代码 
     * @param picType 
     * @return int 
     */  
    private static int getPictureType(String picType){
    
      
    	int format = -1;
        if(picType.equalsIgnoreCase("emf")) format = XWPFDocument.PICTURE_TYPE_EMF;
        else if(picType.equalsIgnoreCase("wmf")) format = XWPFDocument.PICTURE_TYPE_WMF;
        else if(picType.equalsIgnoreCase("pict")) format = XWPFDocument.PICTURE_TYPE_PICT;
        else if(picType.equalsIgnoreCase("jpeg") || picType.equalsIgnoreCase("jpg")) format = XWPFDocument.PICTURE_TYPE_JPEG;
        else if(picType.equalsIgnoreCase("png")) format = XWPFDocument.PICTURE_TYPE_PNG;
        else if(picType.equalsIgnoreCase("dib")) format = XWPFDocument.PICTURE_TYPE_DIB;
        else if(picType.equalsIgnoreCase("gif")) format = XWPFDocument.PICTURE_TYPE_GIF;
        else if(picType.equalsIgnoreCase("tiff")) format = XWPFDocument.PICTURE_TYPE_TIFF;
        else if(picType.equalsIgnoreCase("eps")) format = XWPFDocument.PICTURE_TYPE_EPS;
        else if(picType.equalsIgnoreCase("bmp")) format = XWPFDocument.PICTURE_TYPE_BMP;
        else if(picType.equalsIgnoreCase("wpg")) format = XWPFDocument.PICTURE_TYPE_WPG;
        else {
    
    
            System.err.println("Unsupported picture: " + picType +". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
        }
        return format;
    }
   
      
     
    /**
     * 获取
     * @param filepath
     * @return
     */
    public static String getFileType(String filepath){
    
    
    	String fileType = "";
    	if(filepath!=null){
    
    
			File file = new File(filepath);
			String fileName = file.getName();
			int index = fileName.lastIndexOf(".");
			if(index>=0){
    
    
				fileType = fileName.substring(index+1,fileName.length());
			}
    	}
		return fileType;
    }
}

Fourth, the effect after operation

After running the JdbcTest startup class, the effect of the console is as follows:
insert image description here
the generated files are as follows:
insert image description here

Guess you like

Origin blog.csdn.net/qq_44723773/article/details/130614939