最近一个项目要做彻底改版,数据库需要重构。结果收到一堆WORD的字典表,按上面的要求开库建表。类似于这种:

用VBScript将WORD字典表或TXT导入PowerDesigner来批量生成表_图片

正常情况下,接下来就是手指运动,Ctrl+C和Ctrl+V在Word和PowerDesigner之间运动。手都酸了,于是就想:有没有办法批量导入呢?

于是GOOGLE一下,发现了一篇参考文章:http://www.cnblogs.com/pc-funning/archive/2009/01/21/1379537.html.然后就自己开始捣鼓捣鼓。。。

先把word内容贴到Excel里,然后再把Excel另存为用制表符分隔的CSV文件,然后再用txt打开此CSV文件,再整理了一下格式。

但是用制表符分隔时,总有错误,一怒之下,就把所有制表符用“|”代替之。结果,好了,导入无误。

我的TXT格式如下:

表名|说明

字段名(也是Code名)|数据类型|数据长度|默认值|字段说明

Bank|银行表
BankID|int|4|1|
BankName|nvarchar|50||银行名称
BankImage|varchar|100|N'Blank.jpg'|银行图片
BankState|bit|1|0|可用:0否,1是

vbscript如下:

Option Explicit

Dim system, file
Set system = CreateObject("Scripting.FileSystemObject") 


Dim ForReading, ForWriting, ForAppending
dim str
dim tittle
dim first
ForReading   = 1 ' 设置文件只读 
ForWriting   = 2 ' 设置文件写入
ForAppending = 8 ' 设置文件追加


Set file = system.OpenTextFile("D:\table.txt", ForReading)'打开文本文档
Dim noLine
Dim Tab  '定义一个表,vbscript中变量没有那么严格的类型,但此变量将来将用来表示table
ValidationMode = True
Dim mdl ' 定义当前激活的模型,也就是mdl
Dim Col
dim dm, dmstr
Dim SSS
Dim isNewTable

Set mdl = ActiveModel '获取当前激活模型

    set Tab = mdl.Tables.CreateNew
    isNewTable = True

    first=file.readline '读文档按行读
    tittle=split(first,"|") '以空格分隔划分入数组,获取的是表的属性,可以获取更多属性,根据实际情况而定
    tab.name=tittle(0) 'name
    tab.code=tittle(0) 'code
    tab.comment=tittle(1) 'comment

Do While file.AtEndOfStream <> True '循环读取文档的每一行
   SSS = file.ReadLine
   str=split(SSS,"|")

   If SSS <> "" Then
     isNewTable = False
   Else
    isNewTable = True
   End If
   
   If isNewTable = True Then
    first=file.readline '读文档按行读
     tittle=split(first,"|")
    set Tab = mdl.Tables.CreateNew  '创建新表,这是读到空行时的表现,自己用来警示
     tab.name=tittle(0) 'name
     tab.code=tittle(0) 'code
    msgbox(tittle(0))
     tab.comment=tittle(1) 'comment
   Else
    set Col=tab.Columns.CreateNew '创建一行字段
    Col.name = str(0) '依次设置属性,同表的属性,字段熟悉也可以设置更多,根据实际情况
    Col.Code= str(0)
    '这里的判断主要是因为我的txt还有一个数据类型长度的值,但这些类型是不能指定长度的。
    ’如果你的txt整理成:字段名(也是Code名)|数据类型(数据长度)|字段说明;那么下面的判断和异常处理都免了。
    '因为我拿到的word字典表就是这个样子,也没有办法,如果每个字段去整理出来,那就。。。
    if LCase(str(1))<>"int" and Lcase(str(1))<>"bit" and Lcase(str(1))<>"datetime" and Lcase(str(1))<>"tinyint" and Left(Lcase(str(1)),7)<>"decimal" then
     on error resume next
    col.datatype=str(1)+"("+str(2)+")"
    if err<>0 then
     msgbox(str(0)+"-"+str(1)+":"+Err.Description )
    end if
    else
    col.datatype=str(1)
    end if
    col.Comment=str(4)
    col.defaultValueDisplayed=str(3)
   End If
Loop
file.Close

Ctrl+Shift+X调出脚本执行窗口,执行一下,pdf里新增了一大堆表,心情大好。但是有些设定还是需要去手动去做,如键,关系等等。