C# 生成數據字典(Word 表格)

先看一張效果圖:


如果您覺得您會了,請繞道...

說說怎麼實現的

第一步:添加引用

Microsoft.Office.Interop.Word

第二步:說說精髓部分,並非完整代碼,末尾 附上 源碼

                    Microsoft.Office.Interop.Word.Application app = null;
                    Microsoft.Office.Interop.Word.Document doc = null;

                    object oMissing = System.Reflection.Missing.Value;
                    //**創建Word應用程序
                    app = new Microsoft.Office.Interop.Word.Application();
                    //**添加一個word文檔
                    doc = app.Documents.Add();
                    //**輸出大標題
                    app.Selection.Font.Bold = 500;
                    app.Selection.Font.Size = 16;
                    //**水平居中
                    app.Selection.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    //**垂直居中
                    app.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

                    //**設置頁邊距
                    app.ActiveDocument.PageSetup.LeftMargin = app.CentimetersToPoints(float.Parse("1"));
                    app.ActiveDocument.PageSetup.RightMargin = app.CentimetersToPoints(float.Parse("1"));

                    //**可自己更改
                    app.Selection.Text = "數據庫:LifeNote"; 

                    //**換行添加表格
                    object line = Microsoft.Office.Interop.Word.WdUnits.wdLine;
                    app.Selection.MoveDown(ref line, oMissing, oMissing);
                    //**換三次行
                    app.Selection.TypeParagraph();
                    app.Selection.TypeParagraph();
                    app.Selection.TypeParagraph();
                    Microsoft.Office.Interop.Word.Table table = null;
                    //**dtList 爲 一個CheckedListBox  用於列出 對應數據庫的所有表,此處是用於遍歷選中的表
                    foreach (var item in dtList.CheckedItems)
                    {
                        #region 添加多個表格
                        //**此處獲取對應表的字段屬性
                        //**getTableInfoCmdText方法獲取sql 語句                        
                        DataSet ds = SqlHelper.ExecuteDataset(conn, System.Data.CommandType.Text, string.Format(getTableInfoCmdText(item.ToString()), item.ToString()));

                        int rows = ds.Tables[0].Rows.Count + 3;
                        //**固定12列
                        int cols = 12;
                        //**創建表格
                        //table  = app.Selection.Tables.Add(range, rows, cols, ref oMissing, ref oMissing);
                        table = doc.Tables.Add(app.Selection.Range, rows, cols, ref oMissing, ref oMissing);

                        //**表格邊框樣式
                        table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                        table.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                        //**設置表格字體大小粗細
                        table.Range.Font.Size = 10;
                        table.Range.Font.Bold = 0;

                        //**設置表格標題
                        int rowIndex = 1;
                        table.Cell(rowIndex, 1).Range.Text = "表名";
                        table.Cell(rowIndex, 3).Range.Text = item.ToString() + "(  )";
                        table.Rows[1].Range.Font.Bold = 2;
                        //**合併2個單元格
                        table.Cell(1, 1).Merge(table.Cell(1, 2));
                        //**合併10個單元格
                        table.Cell(1, 2).Merge(table.Cell(1, 11));
                        rowIndex++;
                        #region 表頭
                        //**設置單元格背景色
                        //table.Rows[1].Shading.ForegroundPatternColor
                        table.Rows[1].Range.Shading.ForegroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorPaleBlue;
                        table.Rows[2].Range.Shading.ForegroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorPaleBlue;
                        table.Cell(rowIndex, 1).Range.Text = "字段名";
                        table.Cell(rowIndex, 2).Range.Text = "中文名";
                        table.Cell(rowIndex, 3).Range.Text = "類型";
                        table.Cell(rowIndex, 4).Range.Text = "長度";
                        table.Cell(rowIndex, 5).Range.Text = "佔用位元組數";
                        table.Cell(rowIndex, 6).Range.Text = "主鍵";
                        table.Cell(rowIndex, 7).Range.Text = "外鍵";
                        table.Cell(rowIndex, 8).Range.Text = "唯一鍵";
                        table.Cell(rowIndex, 9).Range.Text = "標識";
                        table.Cell(rowIndex, 10).Range.Text = "小數位";
                        table.Cell(rowIndex, 11).Range.Text = "允許空";
                        table.Cell(rowIndex, 12).Range.Text = "默認值";
                        table.Rows[2].Range.Font.Bold = 2;
                        #endregion

                        rowIndex++;
                        //**ds.Tables[0] 指遍歷到的表
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            #region 行數據
                            table.Cell(rowIndex, 1).Range.Text = dr["field"].ToString();
                            //table.Cell(rowIndex, 1).Width = 60;
                            table.Cell(rowIndex, 2).Range.Text = dr["chins"].ToString();
                            table.Cell(rowIndex, 3).Range.Text = dr["types"].ToString();
                            //**此處是由於 字段長度爲max 獲取到的數據爲-1 故轉爲max
                            table.Cell(rowIndex, 4).Range.Text = dr["length"].ToString().Equals("-1") ? "max" : dr["length"].ToString();
                            table.Cell(rowIndex, 5).Range.Text = dr["lengthdel"].ToString().Equals("-1") ? "max" : dr["lengthdel"].ToString();
                            table.Cell(rowIndex, 6).Range.Text = dr["pk"].ToString();
                            table.Cell(rowIndex, 7).Range.Text = dr["fk"].ToString();
                            table.Cell(rowIndex, 8).Range.Text = dr["uq"].ToString();
                            table.Cell(rowIndex, 9).Range.Text = dr["bs"].ToString();
                            table.Cell(rowIndex, 10).Range.Text = dr["decl"].ToString();
                            table.Cell(rowIndex, 11).Range.Text = dr["nuls"].ToString();
                            table.Cell(rowIndex, 12).Range.Text = dr["defuat"].ToString();
                            #endregion
                            rowIndex++;
                        }
                        table.Cell(rowIndex, 1).Range.Text = "備註:";
                        //**合併12個單元格
                        table.Cell(rowIndex, 1).Merge(table.Cell(rowIndex, 12));

                        //**不加此處容易出現第二個表格嵌入在第一個表格的第一個單元格內
                        //**防止多個表格出現重合情況
                        object WdStory = Microsoft.Office.Interop.Word.WdUnits.wdStory;
                        app.Selection.EndKey(ref WdStory, ref oMissing);
                        object count = 14;
                        object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;
                        app.Selection.MoveDown(ref WdLine, ref count, ref oMissing);
                        app.Selection.TypeParagraph();
                    }

                    //導出到文件
                    string newFile = "數據字典 LifeNote.doc";
                    //**此處暫未寫死路徑
                    string physicNewFile = @"C:\" + newFile;
                    //**創建成功
                    doc.SaveAs(physicNewFile,
                    oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                    oMissing, oMissing, oMissing, oMissing, oMissing, oMissing); 

                    注意關閉 
                    if (doc != null)
                    {
                      doc.Close();//關閉文檔
                    }
                    if (app != null)
                    {
                      app.Quit();//退出應用程序
                    }

                    getTableInfoCmdText方法
        /// <summary>
        /// 獲取指定表的結構信息
        /// </summary>
        private string getTableInfoCmdText(string tableName)
        {
            return string.Format(@"
            SELECT   
            num         =   A.COLORDER, 
            field       =   A.NAME,  
            chins       =   ISNULL(G.[VALUE], ' ') , 
            types         =   B.NAME, 
            length         =   COLUMNPROPERTY(A.ID,A.NAME, 'PRECISION '),
            lengthdel =   A.LENGTH, 
            pk         =   CASE   WHEN   EXISTS(SELECT   1   FROM   SYSOBJECTS   WHERE   XTYPE= 'PK '   AND   PARENT_OBJ=A.ID   AND   NAME   IN   ( 
            SELECT   NAME   FROM   SYSINDEXES   WHERE   INDID   IN( 
            SELECT   INDID   FROM   SYSINDEXKEYS   WHERE   ID   =   A.ID   AND   COLID=A.COLID)))   THEN   '是'   ELSE   ' '   END, --主鍵結束
            fk         = (case  when(select count(*) from (select OBJECT_NAME(f.fkeyid) as fname, col.name, f.constid as temp from syscolumns col,sysforeignkeys f where f.fkeyid=col.id and f.fkey=col.colid) ft where ft.fname = d.name and ft.name=a.name)>0 then '是' else '' end), --外鍵結束
            uq         =(case when(select count(COLUMN_NAME) from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where CONSTRAINT_NAME in 
                (SELECT name FROM sys.key_constraints where object_name(parent_object_id)=d.name AND type='UQ') and COLUMN_NAME=a.name)>0 then '是' else '' end) ,--唯一鍵結束    
            bs         =   CASE   WHEN   COLUMNPROPERTY(   A.ID,A.NAME, 'ISIDENTITY ')=1   THEN   '是'ELSE   ' '   END, 
            decl       =   ISNULL(COLUMNPROPERTY(A.ID,A.NAME, 'SCALE '),0), 
            nuls       =   CASE   WHEN   A.ISNULLABLE=1   THEN   '允許'ELSE   ' '   END, 
            defuat       =   ISNULL(E.TEXT, ' ')
            FROM  SYSCOLUMNS   A 
            LEFT   JOIN  SYSTYPES   B   
            ON   A.XUSERTYPE=B.XUSERTYPE 
            INNER   JOIN   SYSOBJECTS   D   
            ON   A.ID=D.ID     AND   D.XTYPE= 'U '   AND     D.NAME <> 'DTPROPERTIES ' 
            LEFT   JOIN   SYSCOMMENTS   E   
            ON   A.CDEFAULT=E.ID 
            LEFT   JOIN   sys.extended_properties   G   
            ON   A.ID=G.major_id   AND   A.COLID=G.minor_id     
            LEFT   JOIN   sys.extended_properties   F   
            ON   D.ID=F.major_id   AND   F.minor_id=0 
            WHERE D.NAME='{0}'
            ORDER   BY   A.ID,A.COLORDER
            ", tableName);
        }
最後,謝謝您耐心的閱讀,

此處附上源碼  數據字典生成器

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章