首页 > 代码库 > C#操作PowerDesigner代码

C#操作PowerDesigner代码

首先,程序的界面如下:

这里一定要使用OpenFileDialog控件,然后该页面代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace DBDesign
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.Filter = "pdm文件(*.pdm)|*.pdm";
            this.openFileDialog1.Multiselect = false;

            if (this.openFileDialog1.ShowDialog() == DialogResult.OK) 
            {
                this.label2.Text = this.openFileDialog1.FileName;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                PdmReader mTest = new PdmReader(this.label2.Text);
                Form2 f2 = new Form2(mTest, this.label2.Text);
                f2.Show();
                this.Visible = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }
    }
}

然后第二个页面界面如下:

 

这个界面的代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace DBDesign
{
    public partial class Form2 : Form
    {
        private PdmReader pr = new PdmReader();

        private string path = string.Empty;

        public Form2(PdmReader pr, string path)
        {
            InitializeComponent();

            this.pr = pr;
            this.path = path;
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            pr.InitData();

            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.DataSource = pr.Tables;

            string[] names = null;
            List<string> hms = new List<string>();
            List<string> res = null;
            for (int i = 0; names != null && i < names.Length; i++) 
            {
                string[] str = names[i].Split(new char[] { ! }, StringSplitOptions.RemoveEmptyEntries);
                res = hms.FindAll(M => M.Equals(str[0].Substring(24)));
                if (!(res != null && res.Count > 0)) 
                {
                    hms.Add(str[0].Substring(24));
                }
            }
            foreach (string s in hms) 
            {
                this.comboBox1.Items.Add(s);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Visible = false;
            Form1 f1 = new Form1();
            f1.Show();
        }

        private void Form2_FormClosed(object sender, FormClosedEventArgs e)
        {
            System.Windows.Forms.Application.Exit();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (this.comboBox1.SelectedItem != null && !this.comboBox1.SelectedItem.Equals("")) 
            {
                FileInfo file = new FileInfo(path);
                if (!Directory.Exists("D:\\work\\Test\\XML\\" + file.Name.Split(new char[] { . }, StringSplitOptions.RemoveEmptyEntries)[0])) 
                {
                    Directory.CreateDirectory("D:\\work\\Test\\XML\\" + file.Name.Split(new char[] { . }, StringSplitOptions.RemoveEmptyEntries)[0]);
                }
                if (Directory.Exists("D:\\work\\Test\\XML\\" + file.Name.Split(new char[] { . }, StringSplitOptions.RemoveEmptyEntries)[0] + "\\" + this.comboBox1.SelectedItem.ToString() + ".txt")) 
                {
                    File.Delete("D:\\work\\Test\\XML\\" + file.Name.Split(new char[] { . }, StringSplitOptions.RemoveEmptyEntries)[0] + "\\" + this.comboBox1.SelectedItem.ToString() + ".txt");
                }
                string str = string.Empty;
                foreach (DataGridViewRow dr in this.dataGridView1.Rows) 
                {
                    if (dr.Cells[0].Value != null && int.Parse(dr.Cells[0].Value.ToString()) == 1)   
                    {
                        str += dr.Cells[1].Value.ToString() + "|";
                    }
                }
                if (str.Length > 0) 
                {
                    str = str.Substring(0, str.Length - 1);
                }
                FileStream fs = new FileStream("D:\\work\\Test\\XML\\" + file.Name.Split(new char[] { . }, StringSplitOptions.RemoveEmptyEntries)[0] + "\\" + this.comboBox1.SelectedItem.ToString() + ".txt", FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);
                sw.Write(str);
                sw.Flush();
                sw.Close();
                fs.Close();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int n = 1;
            FileInfo file = new FileInfo(path);
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();
            app.Visible = false;
            Workbook wb = app.Workbooks.Add(true);
            Worksheet ws = (Worksheet)wb.ActiveSheet;
            ws.Name = "所有表";
            ((Microsoft.Office.Interop.Excel.Range)ws.Columns["B", Type.Missing]).ColumnWidth = 25.50;
            ((Microsoft.Office.Interop.Excel.Range)ws.Columns["A", Type.Missing]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
            ((Microsoft.Office.Interop.Excel.Range)ws.Columns["E", Type.Missing]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
            ((Microsoft.Office.Interop.Excel.Range)ws.Columns["F", Type.Missing]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
            ((Microsoft.Office.Interop.Excel.Range)ws.Columns["C", Type.Missing]).ColumnWidth = 43.50;
            ((Microsoft.Office.Interop.Excel.Range)ws.Columns["D", Type.Missing]).ColumnWidth = 10.00;
            ((Microsoft.Office.Interop.Excel.Range)ws.Columns["E", Type.Missing]).ColumnWidth = 8.50;
            ((Microsoft.Office.Interop.Excel.Range)ws.Columns["F", Type.Missing]).ColumnWidth = 8.50;
            Range r = ws.get_Range(ws.Cells[1,1],ws.Cells[1,6]);
            r.Interior.ColorIndex = 37;
            r.Font.Size = 12;
            r.Font.Bold = true;
            Borders borders = r.Borders;
            borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
            ws.Cells[n, 1] = "序号";
            ws.Cells[n, 2] = "表名";
            ws.Cells[n, 3] = "表说明";
            ws.Cells[n, 4] = "字段类型";
            ws.Cells[n, 5] = "长度";
            ws.Cells[n, 6] = "允许空";

            n = 2;

            List<string> list = new List<string>();
            for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
            {
                DataGridViewRow dr = this.dataGridView1.Rows[i];
                string str = dr.Cells[1].Value.ToString();
                if (dr.Cells["cbxTable"].Value != null && dr.Cells["cbxTable"].Value.ToString().Equals("1")) 
                {
                    list.Add(dr.Cells[1].Value.ToString());
                }
            }

            foreach (TableInfo table in pr.Tables) 
            {
                bool print = false;
                if (this.checkBox1.Checked)
                {
                    print = true;
                }
                else 
                {
                    foreach (string s in list) 
                    {
                        if (s.Equals(table.Code)) 
                        {
                            print = true;
                        }
                    }
                }
                if (print) 
                {
                    Range rt = ws.get_Range(ws.Cells[n, 1], ws.Cells[n, 6]);
                    rt.Interior.ColorIndex = 35;
                    rt.Font.Size = 12;
                    Borders border = rt.Borders;
                    border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    ws.Cells[n, 1] = "T";
                    ws.Cells[n, 2] = table.Code;
                    ws.Cells[n, 3] = table.Comment;
                    ws.Cells[n, 4] = "";
                    ws.Cells[n, 5] = "";
                    ws.Cells[n, 6] = "";

                    n = n + 1;

                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        Range rtc = ws.get_Range(ws.Cells[n, 1], ws.Cells[n, 6]);
                        rtc.Font.Size = 12;
                        Borders borderc = rtc.Borders;
                        borderc.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                        ws.Cells[n, 1] = i + 1;
                        ws.Cells[n, 2] = table.Columns[i].Code;
                        ws.Cells[n, 3] = table.Columns[i].Comment;
                        ws.Cells[n, 4] = table.Columns[i].DataType.Contains("(") ? table.Columns[i].DataType.Split(new char[] { ( }, StringSplitOptions.RemoveEmptyEntries)[0] : table.Columns[i].DataType;
                        if (table.Columns[i].DataType.Equals("int"))
                        {
                            ws.Cells[n, 5] = 10;
                        }
                        else if (table.Columns[i].DataType.Equals("datetime"))
                        {
                            ws.Cells[n, 5] = 23;
                        }
                        else
                        {
                            ws.Cells[n, 5] = table.Columns[i].Length;
                        }
                        ws.Cells[n, 6] = table.Columns[i].Mandatory ? "" : "";

                        if (table.Primary != null) 
                        {
                            foreach (string pk in table.Primary)
                            {
                                if (pk.Equals(table.Columns[i].ColumnId))
                                {
                                    rtc.Interior.ColorIndex = 6;
                                }
                            }
                        }

                        n = n + 1;
                    }
                }
            }

            wb.Saved = true;
            app.ActiveWorkbook.SaveCopyAs("D:\\Test.xlsx");
            MessageBox.Show("over!");
        }
    }
}

然后这里还用到了四个别的类,分别列举一下:

1.TableInfo.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace DBDesign
{
    //表信息
    public class TableInfo
    {
        public TableInfo()
        {
        }
        string tableId;

        public string TableId
        {
            get { return tableId; }
            set { tableId = value; }
        }
        string objectID;

        public string ObjectID
        {
            get { return objectID; }
            set { objectID = value; }
        }
        string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        string code;

        public string Code
        {
            get { return code; }
            set { code = value; }
        }
        int creationDate;

        public int CreationDate
        {
            get { return creationDate; }
            set { creationDate = value; }
        }
        string creator;

        public string Creator
        {
            get { return creator; }
            set { creator = value; }
        }
        int modificationDate;

        public int ModificationDate
        {
            get { return modificationDate; }
            set { modificationDate = value; }
        }
        string modifier;

        public string Modifier
        {
            get { return modifier; }
            set { modifier = value; }
        }
        string comment;

        public string Comment
        {
            get { return comment; }
            set { comment = value; }
        }

        string physicalOptions;

        public string PhysicalOptions
        {
            get { return physicalOptions; }
            set { physicalOptions = value; }
        }


        IList<ColumnInfo> columns;

        public IList<ColumnInfo> Columns
        {
            get { return columns; }
        }

        IList<PdmKey> keys;

        public IList<PdmKey> Keys
        {
            get { return keys; }
        }

        IList<string> primary;

        public IList<string> Primary
        {
            get { return primary; }
            set { primary = value; }
        }

        public void AddColumn(ColumnInfo mColumn)
        {
            if (columns == null)
                columns = new List<ColumnInfo>();
            columns.Add(mColumn);
        }

        public void AddKey(PdmKey mKey)
        {
            if (keys == null)
                keys = new List<PdmKey>();
            keys.Add(mKey);
        }

        public void AddPrimary(string id) 
        {
            if (primary == null)
                primary = new List<string>();
            primary.Add(id);
        }
    }

}

2.PdmReader.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace DBDesign
{
    public class PdmReader
    {
        public const string a = "attribute", c = "collection", o = "object";

        public const string cClasses = "c:Classes";
        public const string oClass = "o:Class";

        public const string cAttributes = "c:Attributes";
        public const string oAttribute = "o:Attribute";

        public const string cTables = "c:Tables";
        public const string oTable = "o:Table";

        public const string cColumns = "c:Columns";
        public const string oColumn = "o:Column";


        XmlDocument xmlDoc;
        XmlNamespaceManager xmlnsManager;
        /// <summary>构造函数 </summary>
        public PdmReader()
        {
            // TODO: 在此处添加构造函数逻辑
            xmlDoc = new XmlDocument();
        }
        /// <summary>构造函数 </summary>
        public PdmReader(string pdm_file)
        {
            PdmFile = pdm_file;
        }

        string pdmFile;

        public string PdmFile
        {
            get { return pdmFile; }
            set
            {
                pdmFile = value;
                if (xmlDoc == null)
                {
                    xmlDoc = new XmlDocument();
                    xmlDoc.Load(pdmFile);
                    xmlnsManager = new XmlNamespaceManager(xmlDoc.NameTable);
                    xmlnsManager.AddNamespace("a", "attribute");
                    xmlnsManager.AddNamespace("c", "collection");
                    xmlnsManager.AddNamespace("o", "object");
                }
            }
        }

        IList<TableInfo> tables;

        public IList<TableInfo> Tables
        {
            get { return tables; }
            set { tables = value; }
        }

        public void InitData()
        {
            if (Tables == null)
                Tables = new List<TableInfo>();
            XmlNode xnTables = xmlDoc.SelectSingleNode("//" + cTables, xmlnsManager);
            foreach (XmlNode xnTable in xnTables.ChildNodes)
            {
                Tables.Add(GetTable(xnTable));
            }
        }

        //初始化"o:Table"的节点
        private TableInfo GetTable(XmlNode xnTable)
        {
            TableInfo mTable = new TableInfo();
            XmlElement xe = (XmlElement)xnTable;
            mTable.TableId = xe.GetAttribute("Id");
            XmlNodeList xnTProperty = xe.ChildNodes;
            foreach (XmlNode xnP in xnTProperty)
            {
                switch (xnP.Name)
                {
                    case "a:ObjectID": mTable.ObjectID = xnP.InnerText;
                        break;
                    case "a:Name": mTable.Name = xnP.InnerText;
                        break;
                    case "a:Code": mTable.Code = xnP.InnerText;
                        break;
                    case "a:CreationDate": mTable.CreationDate = Convert.ToInt32(xnP.InnerText);
                        break;
                    case "a:Creator": mTable.Creator = xnP.InnerText;
                        break;
                    case "a:ModificationDate": mTable.ModificationDate = Convert.ToInt32(xnP.InnerText);
                        break;
                    case "a:Modifier": mTable.Modifier = xnP.InnerText;
                        break;
                    case "a:Comment": mTable.Comment = xnP.InnerText;
                        break;
                    case "a:PhysicalOptions": mTable.PhysicalOptions = xnP.InnerText;
                        break;
                    case "c:Columns": InitColumns(xnP, mTable);
                        break;
                    case "c:Keys": InitKeys(xnP, mTable);
                        break;
                    case "c:PrimaryKey": InitPrimary(xnP, mTable);
                        break;
                }
            }
            return mTable;
        }
        //初始化"c:Columns"的节点
        private void InitColumns(XmlNode xnColumns, TableInfo pTable)
        {
            foreach (XmlNode xnColumn in xnColumns)
            {
                pTable.AddColumn(GetColumn(xnColumn));
            }
        }

        //初始化c:Keys"的节点
        private void InitKeys(XmlNode xnKeys, TableInfo pTable)
        {
            foreach (XmlNode xnKey in xnKeys)
            {
                pTable.AddKey(GetKey(xnKey));
            }
        }

        //初始化c:PrimaryKey的节点
        private void InitPrimary(XmlNode xnKeys, TableInfo pTable) 
        {
            foreach (XmlNode xnKey in xnKeys)
            {
                PdmKey key = GetPrimary(xnKey);
                foreach (PdmKey pk in pTable.Keys) 
                {
                    if (pk.KeyId.Equals(key.KeyId)) 
                    {
                        foreach (ColumnInfo ci in pk.Columns) 
                        {
                            pTable.AddPrimary(ci.ColumnId);
                        }
                    }
                }
            }
        }

        private ColumnInfo GetColumn(XmlNode xnColumn)
        {
            ColumnInfo mColumn = new ColumnInfo();
            XmlElement xe = (XmlElement)xnColumn;
            mColumn.ColumnId = xe.GetAttribute("Id");
            XmlNodeList xnCProperty = xe.ChildNodes;
            foreach (XmlNode xnP in xnCProperty)
            {
                switch (xnP.Name)
                {
                    case "a:ObjectID": mColumn.ObjectID = xnP.InnerText;
                        break;
                    case "a:Name": mColumn.Name = xnP.InnerText;
                        break;
                    case "a:Code": mColumn.Code = xnP.InnerText;
                        break;
                    case "a:CreationDate": mColumn.CreationDate = Convert.ToInt32(xnP.InnerText);
                        break;
                    case "a:Creator": mColumn.Creator = xnP.InnerText;
                        break;
                    case "a:ModificationDate": mColumn.ModificationDate = Convert.ToInt32(xnP.InnerText);
                        break;
                    case "a:Modifier": mColumn.Modifier = xnP.InnerText;
                        break;
                    case "a:Comment": mColumn.Comment = xnP.InnerText;
                        break;
                    case "a:DataType": mColumn.DataType = xnP.InnerText;
                        break;
                    case "a:Length": mColumn.Length = xnP.InnerText;
                        break;
                    case "a:Identity": mColumn.Identity = xnP.InnerText.Equals("Yes") ? true : false;
                        break;
                    case "a:Mandatory": mColumn.Mandatory = xnP.InnerText.Equals("1") ? true : false;
                        break;
                    case "a:PhysicalOptions": mColumn.PhysicalOptions = xnP.InnerText;
                        break;
                    case "a:ExtendedAttributesText": mColumn.ExtendedAttributesText = xnP.InnerText;
                        break;
                }
            }
            return mColumn;
        }

        private PdmKey GetKey(XmlNode xnKey)
        {
            PdmKey mKey = new PdmKey();
            XmlElement xe = (XmlElement)xnKey;
            mKey.KeyId = xe.GetAttribute("Id");
            XmlNodeList xnKProperty = xe.ChildNodes;
            foreach (XmlNode xnP in xnKProperty)
            {
                switch (xnP.Name)
                {
                    case "a:ObjectID": mKey.ObjectID = xnP.InnerText;
                        break;
                    case "a:Name": mKey.Name = xnP.InnerText;
                        break;
                    case "a:Code": mKey.Code = xnP.InnerText;
                        break;
                    case "a:CreationDate": mKey.CreationDate = Convert.ToInt32(xnP.InnerText);
                        break;
                    case "a:Creator": mKey.Creator = xnP.InnerText;
                        break;
                    case "a:ModificationDate": mKey.ModificationDate = Convert.ToInt32(xnP.InnerText);
                        break;
                    case "a:Modifier": mKey.Modifier = xnP.InnerText;
                        break;
                    //还差 <c:Key.Columns>
                    case "c:Key.Columns": GetKeyColumn(xnP, mKey);
                        break;
                }
            }
            return mKey;
        }

        public void GetKeyColumn(XmlNode xnP ,PdmKey mKey) 
        {
            XmlElement xe = (XmlElement)xnP;
            XmlNodeList nodeList = xe.ChildNodes;
            foreach (XmlNode node in nodeList) 
            {
                ColumnInfo ci = new ColumnInfo();
                ci.ColumnId = ((XmlElement)node).GetAttribute("Ref");
                mKey.AddColumn(ci);
            }
        }

        private PdmKey GetPrimary(XmlNode xnKey) 
        {
            PdmKey mKey = new PdmKey();
            XmlElement xe = (XmlElement)xnKey;
            mKey.KeyId = xe.GetAttribute("Ref");
            return mKey;
        }
    }

}

3.PdmKey.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace DBDesign
{
    public class PdmKey
    {
        public PdmKey()
        {
        }

        string keyId;

        public string KeyId
        {
            get { return keyId; }
            set { keyId = value; }
        }
        string objectID;

        public string ObjectID
        {
            get { return objectID; }
            set { objectID = value; }
        }
        string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        string code;

        public string Code
        {
            get { return code; }
            set { code = value; }
        }
        int creationDate;

        public int CreationDate
        {
            get { return creationDate; }
            set { creationDate = value; }
        }
        string creator;

        public string Creator
        {
            get { return creator; }
            set { creator = value; }
        }
        int modificationDate;

        public int ModificationDate
        {
            get { return modificationDate; }
            set { modificationDate = value; }
        }
        string modifier;

        public string Modifier
        {
            get { return modifier; }
            set { modifier = value; }
        }

        IList<ColumnInfo> columns;

        public IList<ColumnInfo> Columns
        {
            get { return columns; }
        }

        public void AddColumn(ColumnInfo mColumn)
        {
            if (columns == null)
                columns = new List<ColumnInfo>();
            columns.Add(mColumn);
        }
    }

}

4.ColumnInfo.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace DBDesign
{
    public class ColumnInfo
    {
        public ColumnInfo()
        { }

        string columnId;

        public string ColumnId
        {
            get { return columnId; }
            set { columnId = value; }
        }
        string objectID;

        public string ObjectID
        {
            get { return objectID; }
            set { objectID = value; }
        }
        string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        string code;

        public string Code
        {
            get { return code; }
            set { code = value; }
        }
        int creationDate;

        public int CreationDate
        {
            get { return creationDate; }
            set { creationDate = value; }
        }
        string creator;

        public string Creator
        {
            get { return creator; }
            set { creator = value; }
        }
        int modificationDate;

        public int ModificationDate
        {
            get { return modificationDate; }
            set { modificationDate = value; }
        }
        string modifier;

        public string Modifier
        {
            get { return modifier; }
            set { modifier = value; }
        }
        string comment;

        public string Comment
        {
            get { return comment; }
            set { comment = value; }
        }
        string dataType;

        public string DataType
        {
            get { return dataType; }
            set { dataType = value; }
        }
        string length;

        public string Length
        {
            get { return length; }
            set { length = value; }
        }
        //是否自增量
        bool identity;

        public bool Identity
        {
            get { return identity; }
            set { identity = value; }
        }
        bool mandatory;
        //禁止为空
        public bool Mandatory
        {
            get { return mandatory; }
            set { mandatory = value; }
        }
        string extendedAttributesText;
        //扩展属性
        public string ExtendedAttributesText
        {
            get { return extendedAttributesText; }
            set { extendedAttributesText = value; }
        }
        string physicalOptions;

        public string PhysicalOptions
        {
            get { return physicalOptions; }
            set { physicalOptions = value; }
        }
    }

}