使用java读取word文档生成oracle建表语句

1、要求:word文档必须是.docx格式,文档格式必须如下:

  1. TABLE_NAME 表注释

序号

字段名称

字段类型

字段描述

规则约束

1

Test_f1

VARCHAR2

字段注释1

2

Test_f2

VARCHAR2

字段注释2

2、添加java的依赖

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.9</version>
</dependency>

3、java代码

package com.main.core;

import java.io.*;
import java.rmi.RemoteException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.*;

public class ReaderWord {
    public static void main(String[] args) throws IOException{
        String sql = "生成sql的文件路径\\sql文件名.sql";
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(sql), "GB2312"));
        String docx = "文件路径\\word文件名.docx";
        XWPFDocument document = read_file(docx);
        read(document, writer);
    }

    public static void read(XWPFDocument document, Writer w) throws IOException {
        w.write("set feedback off\r\n" +
                "set define off\r\n");
        int ind = 0;
        Iterator<IBodyElement> it = document.getBodyElementsIterator();
        StringBuilder result = new StringBuilder();
        String tableName = "";
        String tabComment = "";
        while (it.hasNext()) {
            IBodyElement ibody = it.next();
            if (ibody instanceof XWPFParagraph) { //如果是标题
                XWPFParagraph paragraph = (XWPFParagraph) ibody;
                //run表示相同区域属性相同的字符,结果以‘,’分隔;
                List<XWPFRun> runs =paragraph.getRuns();// paragraph.getRuns();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < runs.size(); i++){
                    String oneparaString = runs.get(i).getText(runs.get(i).getTextPosition());
                    System.out.print(oneparaString);
                    sb.append(oneparaString);
                }
                System.out.println();
                String title = sb.toString();
                String[] arr = title.split(" ");
                if (Pattern.matches("\\w+",arr[0])) {
                    tableName = arr[0];
                    tabComment = title.substring(title.indexOf(' '));
                }
            }
            Map<String, Column> cmap = new LinkedHashMap();
            if (ibody instanceof XWPFTable) { //如果是表格
                if (tableName.equals("")) {
                    System.out.println(tabComment);
                    throw new RemoteException("表名称为空");
                }
                XWPFTable table = (XWPFTable) ibody;
                //行
                int rcount = table.getNumberOfRows();
                int nameid = 0, typeid = 0, commentid = 0;
                for (int i = 0; i < rcount; i++){
                    XWPFTableRow row = table.getRow(i);
                    //列
                    List<XWPFTableCell> cells = row.getTableCells();
                    if (i == 0) {
                        for (int j = 0; j < cells.size(); j++) {
                            if ("字段名称".equals(cells.get(j).getText()) || "字段名".equals(cells.get(j).getText())) {
                                nameid = j;
                            }
                            if ("字段类型".equals(cells.get(j).getText())) {
                                typeid = j;
                            }
                            if ("字段描述".equals(cells.get(j).getText()) || "中文名称".equals(cells.get(j).getText())) {
                                commentid = j;
                            }
                        }
                    } else {
                        Column c = new Column();
                        XWPFTableCell n = cells.get(nameid);
                        String name = n.getText();
                        if (name == null || name.length()==0|| name.contains(" ")) {
                            throw new RuntimeException(tableName + "表的字段名不合法," + name);
                        }
                        c.name = name;
                        XWPFTableCell t = cells.get(typeid);
                        String type = t.getText();
                        c.type = type;
                        XWPFTableCell ct = cells.get(commentid);
                        String comment = ct.getText();
                        c.comment = comment;
                        cmap.put(name, c);
                    }
                }
                w.write("create table ");
                w.write(tableName);
                w.write("\r\n(\r\n");
                int i = 0;
                for (Column c : cmap.values()) {
                    if (i == 0) {
                        w.write("  " + c.name + "  ");
                        if ("VARCHAR2".equals(c.type)) {
                            w.write("VARCHAR2(128)");
                        } else {
                            w.write(c.type);
                        }
                    } else {
                        w.write(",\r\n  " + c.name + "  ");
                        if ("VARCHAR2".equals(c.type)) {
                            w.write("VARCHAR2(128)");
                        } else {
                            w.write(c.type);
                        }
                    }
                    System.out.println(c);
                    i++;
                }
                w.write("\r\n);\r\n");
                w.write("comment on table " + tableName + "\r\n" +
                        "  is '" + tabComment + "';\r\n");
                for (Column c : cmap.values()) {
                    if (c.comment != null && !c.comment.equals("")) {
                        w.write("comment on column " + tableName + "." + c.name + "\r\n" +
                                "  is '" + c.comment.replace('\'','"') + "';\r\n");
                    }
                }
                w.write("\r\n");
                cmap.clear();
                tableName = "";
                ind++;
            }

        }
        w.flush();
        w.close();
    }

    /**
     * 读取文件
     * @param srcPath
     * @return XWPFDocument
     */
    public static XWPFDocument read_file(String srcPath)
    {
        String[] sp = srcPath.split("\\.");
        if ((sp.length > 0) && sp[sp.length - 1].equalsIgnoreCase("docx"))
        {
            try {
                FileInputStream fis = new FileInputStream(srcPath);
                XWPFDocument xdoc = new XWPFDocument(fis);
                XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc);
                return xdoc;
            } catch (IOException e) {
                System.out.println("读取文件出错!");
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    static class Column{
        String name;
        String type;
        String comment;

        @Override
        public String toString() {
            return "Column{" +
                    "name='" + name + '\'' +
                    ", type='" + type + '\'' +
                    ", comment='" + comment + '\'' +
                    '}';
        }
    }
}

4、生成sql结果

set feedback off
set define off
create table TABLE_NAME
(
  Test_f1  VARCHAR2(128),
  Test_f2  VARCHAR2(128)
);
comment on table TABLE_NAME
  is ' 表注释 ';
comment on column TABLE_NAME.Test_f1
  is '字段注释1';
comment on column TABLE_NAME.Test_f2
  is '字段注释2';

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值