1、参考C#代码

  1. using Help.DBAccessLayer.Business;
  2. using Help.DBAccessLayer.Model.SqlGenerator;
  3. using Newtonsoft.Json;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Reflection;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using MSWord = Microsoft.Office.Interop.Word;
  12.  
  13. namespace MainTest.TestModel
  14. {
  15. public class GenerateWordDBDesign
  16. {
  17. /// <summary>
  18. /// 数据库链接字符串
  19. /// </summary>
  20. private string _DbConnectionString = "";
  21.  
  22. /// <summary>
  23. /// 数据库名称
  24. /// </summary>
  25. private string dataBaseName = "master";
  26.  
  27. /// <summary>
  28. /// 是否使用测试数据
  29. /// </summary>
  30. private readonly bool _isMock = true;
  31.  
  32. /// <summary>
  33. /// 由于使用的是COM库,因此有许多变量需要用Missing.Value代替
  34. /// </summary>
  35. private Object Nothing = Missing.Value;
  36.  
  37. /// <summary>
  38. /// 写入黑体文本
  39. /// </summary>
  40. private object unite = MSWord.WdUnits.wdStory;
  41.  
  42. /// <summary>
  43. /// 有长度的类型列表
  44. /// </summary>
  45. private readonly List<string> useLengthList = new List<string>(){
  46. "varchar",
  47. "nvarchar",
  48. };
  49.  
  50. /// <summary>
  51. /// 有小数的类型列表
  52. /// </summary>
  53. private readonly List<string> digitalList = new List<string>()
  54. {
  55. "decimal",
  56. "numeric",
  57. };
  58.  
  59. /// <summary>
  60. /// 获取数据库中的所有表结构信息等,现在的问题是table的cell 的 高度控制不好,内容是上对齐的 20180316
  61. /// </summary>
  62. public void Generate()
  63. {
  64. MDataBaseDefine res = getData();
  65.  
  66. object path; //文件路径变量
  67. MSWord.Application wordApp;
  68. MSWord.Document wordDoc;
  69.  
  70. path = Environment.CurrentDirectory + "\\" + DateTime.Now.ToString("yyyyMMdd") + "_" + this.dataBaseName + ".doc";
  71. wordApp = new MSWord.Application();
  72.  
  73. wordApp.Visible = true;//使文档可见
  74.  
  75. //如果已存在,则删除
  76. if (File.Exists((string)path))
  77. {
  78. File.Delete((string)path);
  79. }
  80.  
  81. //由于使用的是COM库,因此有许多变量需要用Missing.Value代替
  82. wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
  83.  
  84. //页面设置
  85. wordDoc.PageSetup.PaperSize = MSWord.WdPaperSize.wdPaperA4;//设置纸张样式为A4纸
  86. wordDoc.PageSetup.Orientation = MSWord.WdOrientation.wdOrientPortrait;//排列方式为垂直方向
  87. wordDoc.PageSetup.TopMargin = 57.0f;
  88. wordDoc.PageSetup.BottomMargin = 57.0f;
  89. wordDoc.PageSetup.LeftMargin = 57.0f;
  90. wordDoc.PageSetup.RightMargin = 57.0f;
  91. wordDoc.PageSetup.HeaderDistance = 30.0f;//页眉位置
  92.  
  93. wordApp.Selection.ParagraphFormat.LineSpacing = 16f;//设置文档的行间距
  94. wordApp.Selection.ParagraphFormat.FirstLineIndent = ;//首行缩进的长度
  95.  
  96. this.AddHeading1("物理模型设计", wordDoc);
  97. this.DrawTableCountInfo(wordApp, wordDoc, res);
  98.  
  99. wordDoc.Content.InsertAfter("\n");//这一句与下一句的顺序不能颠倒,原因还没搞透
  100. wordApp.Selection.EndKey(ref unite, ref Nothing);//这一句不加,有时候好像也不出问题,不过还是加了安全
  101.  
  102. this.AddHeading2("2 表描述", wordDoc);
  103. int tableIndex = ;
  104. foreach (var item in res.TableList)
  105. {
  106. this.DrawTableDetailInfo(wordApp, wordDoc, tableIndex, item);
  107. tableIndex++;
  108. }
  109.  
  110. wordDoc.Content.InsertAfter("\n");
  111.  
  112. // WdSaveFormat为Word 2003文档的保存格式
  113. // office 2007就是wdFormatDocumentDefault
  114. object format = MSWord.WdSaveFormat.wdFormatDocumentDefault;
  115. //将wordDoc文档对象的内容保存为DOCX文档
  116. wordDoc.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
  117.  
  118. wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
  119. //关闭wordApp组件对象
  120. wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
  121. Console.WriteLine(path + " 创建完毕!");
  122. Console.ReadKey();
  123.  
  124. }
  125.  
  126. /// <summary>
  127. /// 绘制表详细
  128. /// </summary>
  129. /// <param name="wordApp">Word App</param>
  130. /// <param name="wordDoc">Word Doc</param>
  131. /// <param name="tableIndex">表格序号</param>
  132. /// <param name="tableDefine">表定义对象</param>
  133. private void DrawTableDetailInfo(MSWord.Application wordApp, MSWord.Document wordDoc, int tableIndex, MTableDefine tableDefine)
  134. {
  135. // 这一句与下一句的顺序不能颠倒,原因还没搞透
  136. // wordDoc.Content.InsertAfter("\n");
  137.  
  138. // 这一句不加,有时候好像也不出问题,不过还是加了安全
  139. wordApp.Selection.EndKey(ref unite, ref Nothing);
  140.  
  141. this.AddHeading4("2." + tableIndex + " " + tableDefine.TableName + "表的卡片", wordDoc);
  142.  
  143. // 这一句与下一句的顺序不能颠倒,原因还没搞透
  144. // wordDoc.Content.InsertAfter("\n");
  145. // 将光标移动到文档末尾
  146. wordApp.Selection.EndKey(ref unite, ref Nothing);
  147. wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;
  148.  
  149. int tableRow = tableDefine.FieldList.Count + ;
  150. int tableColumn = ;
  151.  
  152. // 定义一个Word中的表格对象
  153. MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range,
  154. tableRow, tableColumn, ref Nothing, ref Nothing);
  155.  
  156. // 默认创建的表格没有边框,这里修改其属性,使得创建的表格带有边框
  157. // 这个值可以设置得很大,例如5、13等等
  158. table.Borders.Enable = ;
  159.  
  160. // 设置 每一列的 宽度
  161. table.Columns[].Width = ;
  162. table.Columns[].Width = ;
  163. table.Columns[].Width = ;
  164. table.Columns[].Width = ;
  165. table.Columns[].Width = ;
  166. table.Columns[].Width = ;
  167. table.Columns[].Width = ;
  168. table.Columns[].Width = ;
  169. table.Columns[].Width = ;
  170.  
  171. // 横向合并
  172. table.Cell(, ).Merge(table.Cell(, ));
  173. table.Cell(, ).Range.Text = tableDefine.TableName;
  174. table.Cell(, ).Range.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorGray25;
  175.  
  176. //表格的索引是从1开始的。
  177. table.Cell(, ).Range.Text = "是否主键";
  178. table.Cell(, ).Range.Text = "字段名";
  179. table.Cell(, ).Range.Text = "字段描述";
  180. table.Cell(, ).Range.Text = "数据类型";
  181. table.Cell(, ).Range.Text = "长度";
  182. table.Cell(, ).Range.Text = "可空";
  183. table.Cell(, ).Range.Text = "约束";
  184. table.Cell(, ).Range.Text = "缺省值";
  185. table.Cell(, ).Range.Text = "备注";
  186.  
  187. for (int i = ; i <= tableRow; i++)
  188. {
  189. int row = i;
  190. var field = tableDefine.FieldList[i - ];
  191.  
  192. // 是否主键
  193. if (field.IsPrimaryKey)
  194. {
  195. table.Cell(row, ).Range.Text = "是";
  196. }
  197. else
  198. {
  199. table.Cell(row, ).Range.Text = "";
  200. }
  201.  
  202. // 字段名
  203. table.Cell(row, ).Range.Text = field.FieldName;
  204. if (string.IsNullOrEmpty(field.FieldNameCH) && field.FieldName == "ID")
  205. {
  206. // 字段描述
  207. table.Cell(row, ).Range.Text = "主键ID";
  208. }
  209. else
  210. {
  211. // 字段描述
  212. table.Cell(row, ).Range.Text = field.FieldNameCH;
  213. }
  214.  
  215. // 数据类型
  216. table.Cell(row, ).Range.Text = field.DataType;
  217.  
  218. if (this.digitalList.Contains(field.DataType))
  219. {
  220. table.Cell(row, ).Range.Text = field.Length.ToString() + "," + field.DigitalLength;
  221. }
  222.  
  223. else if (this.useLengthList.Contains(field.DataType))
  224. {
  225. // 长度
  226. table.Cell(row, ).Range.Text = field.Length.ToString();
  227. }
  228. else
  229. {
  230. table.Cell(row, ).Range.Text = string.Empty;
  231. }
  232.  
  233. // 是否可空
  234. if (field.IsNullable)
  235. {
  236. table.Cell(row, ).Range.Text = "是";
  237. }
  238. else
  239. {
  240. table.Cell(row, ).Range.Text = "否";
  241. }
  242.  
  243. // 约束
  244. table.Cell(row, ).Range.Text = field.ValueConstraint;
  245.  
  246. // 缺省值
  247. table.Cell(row, ).Range.Text = field.DefaultValue;
  248.  
  249. // 备注
  250. table.Cell(row, ).Range.Text = field.ProjectSignificance;
  251. }
  252.  
  253. //设置table样式
  254. //table.Rows.HeightRule = MSWord.WdRowHeightRule.wdRowHeightAtLeast;//高度规则是:行高有最低值下限?
  255. //table.Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8"));//
  256.  
  257. table.Range.Font.Size = 9.5F;
  258. table.Range.Font.Bold = ;
  259. table.Range.Font.Name = "新宋体";
  260.  
  261. table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;//表格文本居中
  262.  
  263. table.Range.Cells.VerticalAlignment = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalBottom;//文本垂直贴到底部
  264.  
  265. // 设置table边框样式
  266. table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;//表格外框是双线
  267. table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;//表格内框是单线
  268.  
  269. // 加粗
  270. table.Rows[].Range.Font.Bold = ;
  271. table.Rows[].Range.Font.Size = 9.5F;
  272.  
  273. // 加粗
  274. table.Rows[].Range.Font.Bold = ;
  275. table.Rows[].Range.Font.Size = 9.5F;
  276. }
  277.  
  278. /// <summary>
  279. /// 添加标题1
  280. /// </summary>
  281. /// <param name="s"></param>
  282. /// <param name="wordDoc"></param>
  283. private void AddHeading1(string s, MSWord.Document wordDoc)
  284. {
  285. //Word段落
  286. Microsoft.Office.Interop.Word.Paragraph p;
  287.  
  288. p = wordDoc.Content.Paragraphs.Add(ref Nothing);
  289.  
  290. //设置段落中的内容文本
  291. p.Range.Text = s;
  292.  
  293. //设置为一号标题
  294. object style = Microsoft.Office.Interop.Word.WdBuiltinStyle.wdStyleHeading1;
  295.  
  296. p.set_Style(ref style);
  297.  
  298. //添加到末尾
  299. p.Range.InsertParagraphAfter(); //在应用 InsertParagraphAfter 方法之后,所选内容将扩展至包括新段落。
  300. }
  301.  
  302. /// <summary>
  303. /// 添加标题2
  304. /// </summary>
  305. /// <param name="s"></param>
  306. /// <param name="wordDoc"></param>
  307. private void AddHeading2(string s, MSWord.Document wordDoc)
  308. {
  309. // Word段落
  310. Microsoft.Office.Interop.Word.Paragraph p;
  311.  
  312. p = wordDoc.Content.Paragraphs.Add(ref Nothing);
  313.  
  314. // 设置段落中的内容文本
  315. p.Range.Text = s;
  316.  
  317. //设置为一号标题
  318. object style = Microsoft.Office.Interop.Word.WdBuiltinStyle.wdStyleHeading2;
  319. p.set_Style(ref style);
  320.  
  321. // 添加到末尾
  322. // 在应用 InsertParagraphAfter 方法之后,所选内容将扩展至包括新段落。
  323. p.Range.InsertParagraphAfter();
  324. }
  325.  
  326. /// <summary>
  327. /// 添加标题4
  328. /// </summary>
  329. /// <param name="s"></param>
  330. /// <param name="wordDoc"></param>
  331. private void AddHeading4(string s, MSWord.Document wordDoc)
  332. {
  333. //Word段落
  334. Microsoft.Office.Interop.Word.Paragraph p;
  335.  
  336. p = wordDoc.Content.Paragraphs.Add(ref Nothing);
  337. //设置段落中的内容文本
  338. p.Range.Text = s;
  339. //设置为一号标题
  340. object style = Microsoft.Office.Interop.Word.WdBuiltinStyle.wdStyleHeading4;
  341. p.set_Style(ref style);
  342. //添加到末尾
  343. p.Range.InsertParagraphAfter(); //在应用 InsertParagraphAfter 方法之后,所选内容将扩展至包括新段落。
  344. }
  345.  
  346. /// <summary>
  347. /// 绘制表清单
  348. /// </summary>
  349. /// <param name="wordApp"></param>
  350. /// <param name="wordDoc"></param>
  351. /// <param name="res"></param>
  352. private void DrawTableCountInfo(MSWord.Application wordApp, MSWord.Document wordDoc, MDataBaseDefine res)
  353. {
  354. // 这一句与下一句的顺序不能颠倒,原因还没搞透
  355. //wordDoc.Content.InsertAfter("\n");
  356.  
  357. // 这一句不加,有时候好像也不出问题,不过还是加了安全
  358. wordApp.Selection.EndKey(ref unite, ref Nothing);
  359.  
  360. this.AddHeading2("1 表清单", wordDoc);
  361.  
  362. //将光标移动到文档末尾
  363. wordApp.Selection.EndKey(ref unite, ref Nothing);
  364. wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;
  365.  
  366. int tableRow = res.TableList.Count + ;
  367. int tableColumn = ;
  368.  
  369. // 定义一个Word中的表格对象
  370. MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range,
  371. tableRow, tableColumn, ref Nothing, ref Nothing);
  372.  
  373. // 默认创建的表格没有边框,这里修改其属性,使得创建的表格带有边框
  374. table.Borders.Enable = ;//这个值可以设置得很大,例如5、13等等
  375.  
  376. // 表格的索引是从1开始的。
  377. table.Cell(, ).Range.Text = "序号";
  378. table.Cell(, ).Range.Text = "代码";
  379. table.Cell(, ).Range.Text = "描述";
  380.  
  381. for (int i = ; i < tableRow; i++)
  382. {
  383. int row = i + ;
  384. var tableInfo = res.TableList[i - ];
  385. table.Cell(row, ).Range.Text = i + ".";
  386. table.Cell(row, ).Range.Text = tableInfo.TableName;
  387. table.Cell(row, ).Range.Text = tableInfo.TableNameCH;
  388. }
  389.  
  390. // 设置table样式
  391. // 高度规则是:行高有最低值下限?
  392. table.Rows.HeightRule = MSWord.WdRowHeightRule.wdRowHeightAtLeast;
  393. //table.Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8"));//
  394.  
  395. table.Range.Font.Size = 11F;
  396. table.Range.Font.Bold = ;
  397. table.Range.Font.Name = "新宋体";
  398.  
  399. // 表格文本居左
  400. table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
  401.  
  402. // 文本垂直贴到底部
  403. table.Range.Cells.VerticalAlignment = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalBottom;
  404.  
  405. // 设置table边框样式
  406. table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;//表格外框是双线
  407. table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;//表格内框是单线
  408.  
  409. // 加粗
  410. table.Rows[].Range.Font.Bold = ;
  411. table.Rows[].Range.Font.Size = 11F;
  412.  
  413. //将第 1列宽度设置为90
  414. table.Columns[].Width = ;
  415.  
  416. //将其他列的宽度都设置为75
  417. for (int i = ; i <= tableColumn; i++)
  418. {
  419. table.Columns[i].Width = ;
  420. }
  421. }
  422.  
  423. /// <summary>
  424. /// 读取数据库及表结构信息
  425. /// </summary>
  426. /// <returns></returns>
  427. private MDataBaseDefine getData()
  428. {
  429. if (_isMock)
  430. {
  431. return new MDataBaseDefine()
  432. {
  433. TableList = new List<MTableDefine>()
  434. {
  435. new MTableDefine(){
  436. FieldList = new List<MFieldDefine>(){
  437. new MFieldDefine(){
  438. DataType = "varchar",
  439. DefaultValue = string.Empty,
  440. DigitalLength = ,
  441. FieldFormat = string.Empty,
  442. FieldName = "ID",
  443. FieldNameCH = string.Empty,
  444. ForeignRelation = string.Empty,
  445. IsNullable = false,
  446. Length = ,
  447. IsAutoIncrement = false,
  448. IsPrimaryKey = true,
  449.  
  450. },
  451. new MFieldDefine(){
  452. DataType = "varchar",
  453. DefaultValue = string.Empty,
  454. DigitalLength = ,
  455. FieldFormat = string.Empty,
  456. FieldName = "UserName",
  457. FieldNameCH = "用户名称",
  458. ForeignRelation = string.Empty,
  459. IsNullable = false,
  460. Length = ,
  461. IsAutoIncrement = false,
  462. IsPrimaryKey = false,
  463.  
  464. }
  465. },
  466. PrimaryKey = "ID",
  467. TableDescrption = string.Empty,
  468. TableName = "User",
  469. TableNameCH = string.Empty
  470. }
  471. }
  472. };
  473. }
  474. else
  475. {
  476. var res = new BGetSchema().GenerateDataBaseDefine(this._DbConnectionString);
  477.  
  478. string json = JsonConvert.SerializeObject(res);
  479.  
  480. // 存个表
  481.  
  482. string fileName = @"C:\Julius_J_Zhu\09DataLayer\MainTest\documents\" + this.dataBaseName + "_JSON_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
  483.  
  484. this.saveFileName(fileName, json);
  485.  
  486. // 去除 含有 下划线的临时表
  487. res.TableList = res.TableList.FindAll(sa => !sa.TableName.Contains("_"));
  488.  
  489. return res;
  490. }
  491. }
  492.  
  493. /// <summary>
  494. /// 保存文件
  495. /// </summary>
  496. /// <param name="name">文件名</param>
  497. /// <param name="str">文件内容</param>
  498. private void saveFileName(string name, string str)
  499. {
  500. using (FileStream fs2 = new FileStream(name, FileMode.Create))
  501. {
  502. StreamWriter sw = new StreamWriter(fs2);
  503.  
  504. //开始写入
  505. sw.Write(str);
  506. //清空缓冲区
  507. sw.Flush();
  508. //关闭流
  509. sw.Close();
  510. }
  511.  
  512. }
  513. }
  514. }

2、所使用的Model类

2.1 数据库类

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace Help.DBAccessLayer.Model.SqlGenerator
  8. {
  9. /// <summary>
  10. /// 数据库定义
  11. /// </summary>
  12. public class MDataBaseDefine
  13. {
  14. /// <summary>
  15. /// 数据库定义
  16. /// </summary>
  17. public string DataBaseName
  18. {
  19. get;
  20. set;
  21. }
  22.  
  23. /// <summary>
  24. /// 数据库类型
  25. /// </summary>
  26. public MDataBaseType DataBaseType
  27. {
  28. get;
  29. set;
  30. }
  31.  
  32. /// <summary>
  33. /// 服务器地址
  34. /// </summary>
  35. public string ServerAddress
  36. {
  37. get;
  38. set;
  39. }
  40.  
  41. /// <summary>
  42. /// 读写账号
  43. /// </summary>
  44. public string ReadAccount
  45. {
  46. get;
  47. set;
  48. }
  49.  
  50. /// <summary>
  51. /// 写账号
  52. /// </summary>
  53. public string WriteAccount
  54. {
  55. get;
  56. set;
  57. }
  58.  
  59. /// <summary>
  60. /// 表列表
  61. /// </summary>
  62. public List<MTableDefine> TableList
  63. {
  64. get;
  65. set;
  66. }
  67. }
  68. }

MDataBaseDefine类

2.2 表结构类

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace Help.DBAccessLayer.Model.SqlGenerator
  8. {
  9. /// <summary>
  10. /// 表定义
  11. /// </summary>
  12. public class MTableDefine
  13. {
  14. /// <summary>
  15. /// 表名(英文)
  16. /// </summary>
  17. public string TableName
  18. {
  19. get;
  20. set;
  21. }
  22.  
  23. /// <summary>
  24. /// 表名(中文)
  25. /// </summary>
  26. public string TableNameCH
  27. {
  28. get;
  29. set;
  30. }
  31.  
  32. /// <summary>
  33. /// 表描述
  34. /// </summary>
  35. public string TableDescrption
  36. {
  37. get;
  38. set;
  39. }
  40.  
  41. /// <summary>
  42. /// 主键
  43. /// </summary>
  44. public string PrimaryKey
  45. {
  46. get;
  47. set;
  48. }
  49.  
  50. /// <summary>
  51. /// 字段定义
  52. /// </summary>
  53. public List<MFieldDefine> FieldList
  54. {
  55. get;
  56. set;
  57. }
  58. }
  59. }

MTableDefine类

2.3 字段类

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace Help.DBAccessLayer.Model.SqlGenerator
  8. {
  9. /// <summary>
  10. /// 表字段定义
  11. /// </summary>
  12. public class MFieldDefine
  13. {
  14. /// <summary>
  15. /// 字段格式
  16. /// </summary>
  17. public string FieldFormat;
  18.  
  19. /// <summary>
  20. /// 序号
  21. /// </summary>
  22. public int Index { get; set; }
  23.  
  24. /// <summary>
  25. /// 字段中文名
  26. /// </summary>
  27. public string FieldNameCH
  28. {
  29. get;
  30. set;
  31. }
  32.  
  33. /// <summary>
  34. /// 字段名
  35. /// </summary>
  36. public string FieldName
  37. {
  38. get;
  39. set;
  40. }
  41.  
  42. /// <summary>
  43. /// 数据类型
  44. /// </summary>
  45. public string DataType
  46. {
  47. get;
  48. set;
  49. }
  50.  
  51. /// <summary>
  52. /// 数据类型长度
  53. /// </summary>
  54. public int Length
  55. {
  56. get;
  57. set;
  58. }
  59.  
  60. /// <summary>
  61. /// 是否可空
  62. /// </summary>
  63. public bool IsNullable
  64. {
  65. get;
  66. set;
  67. }
  68.  
  69. /// <summary>
  70. /// 主键
  71. /// </summary>
  72. public int PrimaryKeyIndex
  73. {
  74. get;
  75. set;
  76. }
  77.  
  78. /// <summary>
  79. /// 外部关系
  80. /// </summary>
  81. public string ForeignRelation
  82. {
  83. get;
  84. set;
  85. }
  86.  
  87. /// <summary>
  88. /// 是否是唯一索引
  89. /// </summary>
  90. public bool IsUniqueIndex
  91. {
  92. get;
  93. set;
  94. }
  95.  
  96. /// <summary>
  97. /// 索引序号
  98. /// </summary>
  99. public int IndexNo
  100. {
  101. get;
  102. set;
  103. }
  104.  
  105. /// <summary>
  106. /// 是否是自增长类型
  107. /// </summary>
  108. public bool IsAutoIncrement
  109. {
  110. get;
  111. set;
  112. }
  113.  
  114. /// <summary>
  115. /// 默认值
  116. /// </summary>
  117. public string DefaultValue
  118. {
  119. get;
  120. set;
  121. }
  122.  
  123. /// <summary>
  124. /// 值约束
  125. /// </summary>
  126. public string ValueConstraint
  127. {
  128. get;
  129. set;
  130. }
  131.  
  132. /// <summary>
  133. /// 项目意义
  134. /// </summary>
  135. public string ProjectSignificance
  136. {
  137. get;
  138. set;
  139. }
  140.  
  141. public int DigitalLength { get; set; }
  142.  
  143. /// <summary>
  144. /// 是否为主键,联合主键可能会有问题
  145. /// </summary>
  146. public bool IsPrimaryKey
  147. {
  148. get;
  149. set;
  150. }
  151. }
  152. }

MFieldDefine类

2.4 数据库类型枚举

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace Help.DBAccessLayer.Model
  8. {
  9. public enum MDataBaseType
  10. {
  11. /// <summary>
  12. /// 未知数据库
  13. /// </summary>
  14. UNKNOW = ,
  15.  
  16. /// <summary>
  17. /// The mysql
  18. /// </summary>
  19. MYSQL = ,
  20.  
  21. /// <summary>
  22. /// The sqlserver
  23. /// </summary>
  24. SQLSERVER = ,
  25.  
  26. /// <summary>
  27. /// DB2
  28. /// </summary>
  29. DB2 =
  30. }
  31. }

MDataBaseType枚举

3、获取数据库结构相关

3.1 获取数据库结构业务层

  1. using Help.DBAccessLayer.Factory;
  2. using Help.DBAccessLayer.Model;
  3. using Help.DBAccessLayer.Model.SqlGenerator;
  4. using IBM.Data.DB2;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Data.OleDb;
  8. using System.Data.SqlClient;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12.  
  13. namespace Help.DBAccessLayer.Business
  14. {
  15. public class BGetSchema
  16. {
  17. public List<MTableDesc> GetTableList(string creator)
  18. {
  19. string connstr = ConnectionFactory.TRSDbConnString;
  20.  
  21. List<MTableDesc> ret = null;
  22.  
  23. using (DB2Connection conn = new DB2Connection(connstr))
  24. {
  25. conn.Open();
  26. var dao = DALFactory.GetSchemaDAO(MDataBaseType.DB2, MDBAccessType.WRITE);
  27.  
  28. ret = dao.GetTableList(conn, creator);
  29. }
  30.  
  31. return ret;
  32. }
  33.  
  34. public List<MColumn> GetColumnList(string tableName)
  35. {
  36. string connstr = ConnectionFactory.TRSDbConnString;
  37. List<MColumn> ret = new List<MColumn>();
  38. using (DB2Connection conn = new DB2Connection(connstr))
  39. {
  40. conn.Open();
  41. var dao = DALFactory.GetSchemaDAO(MDataBaseType.DB2, MDBAccessType.WRITE);
  42.  
  43. ret = dao.GetColumnList(conn, tableName);
  44. }
  45.  
  46. return ret;
  47. }
  48.  
  49. public MDataBaseDefine GenerateDataBaseDefine(string connstr)
  50. {
  51. MDataBaseDefine ret = null;
  52. using (SqlConnection conn = new SqlConnection(connstr))
  53. {
  54. conn.Open();
  55. var dao = DALFactory.GetSchemaDAO(MDataBaseType.SQLSERVER, MDBAccessType.READONLY);
  56. ret = dao.GenerateDataBaseDefine(conn);
  57. }
  58.  
  59. return ret;
  60. }
  61. }
  62. }

BGetSchema类

3.2 获取数据库结构工厂
  1. using Help.DBAccessLayer.DB2DAL;
  2. using Help.DBAccessLayer.IDAL;
  3. using Help.DBAccessLayer.Model;
  4. using Help.DBAccessLayer.MySQLDAL;
  5.  
  6. using SQLServer = Help.DBAccessLayer.SQLServer;
  7. using Help.DBAccessLayer.OleDbDAL;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13.  
  14. namespace Help.DBAccessLayer.Factory
  15. {
  16. public class DALFactory
  17. {
  18. public static IGetSchema GetSchemaDAO(MDataBaseType dbType, MDBAccessType accessType)
  19. {
  20. switch (dbType)
  21. {
  22. case MDataBaseType.DB2:
  23. return new DGetSchema();
  24. case MDataBaseType.SQLSERVER:
  25. return new Help.DBAccessLayer.SQLServer.DGetSchema();
  26. }
  27.  
  28. throw new Exception(string.Format("未实现的IGetSchema接口:数据库类型:{0},数据库访问类型:{1}", dbType.ToString(), accessType.ToString()));
  29. }
  30. }
  31. }

3.3 DGetSchema 获取数据库结构 SQL 实现

  1. using Help.DBAccessLayer.Model;
  2. using Help.DBAccessLayer.Model.SqlGenerator;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9.  
  10. namespace Help.DBAccessLayer.IDAL
  11. {
  12. public interface IGetSchema
  13. {
  14. MDataBaseDefine GenerateDataBaseDefine(System.Data.IDbConnection conn);
  15. }
  16. }
  1. using Help.DBAccessLayer.IDAL;
  2. using Help.DBAccessLayer.Model.SqlGenerator;
  3. using Help.DBAccessLayer.Util;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Data;
  7. using System.Data.SqlClient;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11.  
  12. namespace Help.DBAccessLayer.SQLServer
  13. {
  14. public class DGetSchema : IGetSchema
  15. {
  16. public MDataBaseDefine GenerateDataBaseDefine(System.Data.IDbConnection conn)
  17. {
  18. MDataBaseDefine database = new MDataBaseDefine();
  19. database.TableList = new List<MTableDefine>();
  20.  
  21. // 获取所有表名
  22. List<string> tableNameList = this.GetTableNameList(conn);
  23.  
  24. foreach (var tableName in tableNameList)
  25. {
  26. var table = this.GetTableDefine(conn, tableName);
  27. database.TableList.Add(table);
  28. }
  29.  
  30. // 填充索引信息
  31. List<MTableIndex> indexList = this.GetIndexInfo(conn);
  32.  
  33. var group = from p in indexList
  34. group p by new { p.TableName } into g
  35. select new { g.Key };
  36. foreach (var g in group)
  37. {
  38. var tableFind = database.TableList.Find(sa => sa.TableName == g.Key.TableName);
  39. if (tableFind != null)
  40. {
  41. var columns = tableFind.FieldList;
  42. var indexs = indexList.FindAll(sa => sa.TableName == g.Key.TableName);
  43.  
  44. indexs.ForEach(sa =>
  45. {
  46. var column = columns.Find(p => p.FieldName == sa.ColumnName);
  47. if (sa.IsUnique)
  48. {
  49. column.IsUniqueIndex = true;
  50. }
  51. else
  52. {
  53. column.IndexNo = columns.Max(q => q.IndexNo) + ;
  54. }
  55. });
  56. }
  57. }
  58.  
  59. return database;
  60. }
  61.  
  62. private List<string> GetTableNameList(System.Data.IDbConnection conn)
  63. {
  64. string queryTableListSql = "SELECT name FROM SYSOBJECTS WHERE TYPE='U' and category=0 order by name;";
  65. SqlCommand comm = new SqlCommand(queryTableListSql, (SqlConnection)conn);
  66. SqlDataReader reader = comm.ExecuteReader();
  67.  
  68. List<string> tableNameList = new List<string>();
  69.  
  70. while (reader.Read())
  71. {
  72. string name = reader["name"] == DBNull.Value ? string.Empty : reader["name"].ToString();
  73. tableNameList.Add(name);
  74. }
  75.  
  76. return tableNameList;
  77. }
  78.  
  79. private MTableDefine GetTableDefine(System.Data.IDbConnection conn, string tableName)
  80. {
  81. MTableDefine table = new MTableDefine();
  82. table.TableName = tableName;
  83. string sql = string.Format(@"
  84. SELECT
  85. TableName = case when a.colorder=1 then d.name else '' end,
  86. TableNameCH = case when a.colorder=1 then isnull(f.value,'') else '' end,
  87. FieldIndex = a.colorder,
  88. FieldName = a.name,
  89. IsIdentity = case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then 'true'else 'false' end,
  90. IsPrimaryKey = case when exists(SELECT 1 FROM sysobjects where xtype='PK' and parent_obj=a.id and name in (
  91. SELECT name FROM sysindexes WHERE indid in( SELECT indid FROM sysindexkeys WHERE id = a.id AND colid=a.colid))) then 'true' else 'false' end,
  92. DataType = b.name,
  93. DataTypeLength = COLUMNPROPERTY(a.id,a.name,'PRECISION'),
  94. DigitalLength = isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0),
  95. IsNullable = case when a.isnullable=1 then 'true'else 'false' end,
  96. DefaultValue = isnull(e.text,''),
  97. FieldNameCH = isnull(g.[value],'')
  98. FROM
  99. syscolumns a
  100. left join
  101. systypes b
  102. on
  103. a.xusertype=b.xusertype
  104. inner join
  105. sysobjects d
  106. on
  107. a.id=d.id and d.xtype='U' and d.name<>'dtproperties'
  108. left join
  109. syscomments e
  110. on
  111. a.cdefault=e.id
  112. left join
  113. sys.extended_properties g
  114. on
  115. a.id=G.major_id and a.colid=g.minor_id
  116. left join
  117. sys.extended_properties f
  118. on
  119. d.id=f.major_id and f.minor_id=0
  120. where
  121. d.name='{0}' --如果只查询指定表,加上此红色where条件,tablename是要查询的表名;去除红色where条件查询说有的表信息
  122. order by
  123. a.id,a.colorder;", tableName);
  124.  
  125. SqlCommand comm = new SqlCommand(sql, (SqlConnection)conn);
  126. SqlDataReader reader = comm.ExecuteReader();
  127. List<MFieldDefine> fieldList = new List<MFieldDefine>();
  128. while (reader.Read())
  129. {
  130. MFieldDefine field = new MFieldDefine();
  131. table.TableNameCH = reader["TableNameCH"] == DBNull.Value ? string.Empty : reader["TableNameCH"].ToString();
  132. field.Index = DBUtil.GetDBValueInt(reader, "FieldIndex", );
  133. field.FieldName = DBUtil.GetDBValueStr(reader, "FieldName", string.Empty);
  134. field.IsAutoIncrement = DBUtil.GetDBValueBool(reader, "IsIdentity", false);
  135.  
  136. bool IsPrimaryKey = DBUtil.GetDBValueBool(reader, "IsPrimaryKey", false);
  137. int maxPrimaryKeyIndex = fieldList != null && fieldList.Count > ? fieldList.Max(sa => sa.PrimaryKeyIndex) : ;
  138.  
  139. if (IsPrimaryKey)
  140. {
  141. field.PrimaryKeyIndex = maxPrimaryKeyIndex + ;
  142. }
  143.  
  144. field.IsPrimaryKey = IsPrimaryKey;
  145.  
  146. field.DataType = DBUtil.GetDBValueStr(reader, "DataType", string.Empty);
  147. field.Length = DBUtil.GetDBValueInt(reader, "DataTypeLength", );
  148. field.DigitalLength = DBUtil.GetDBValueInt(reader, "DigitalLength", );
  149. field.IsNullable = DBUtil.GetDBValueBool(reader, "IsNullable", false);
  150. field.DefaultValue = DBUtil.GetDBValueStr(reader, "DefaultValue", string.Empty);
  151.  
  152. // 处理默认值
  153. if (!string.IsNullOrEmpty(field.DefaultValue))
  154. {
  155. string[] twoBracketsSpecial = { "int", "tinyint" };
  156.  
  157. if (twoBracketsSpecial.Contains(field.DataType.ToLower()))
  158. {
  159. field.DefaultValue = field.DefaultValue.Replace("(", string.Empty).Replace(")", string.Empty);
  160. }
  161. else
  162. {
  163. // 只有一个括号
  164. field.DefaultValue = field.DefaultValue.Substring(, field.DefaultValue.Length - );
  165. }
  166. }
  167.  
  168. field.FieldNameCH = DBUtil.GetDBValueStr(reader, "FieldNameCH", string.Empty);
  169. fieldList.Add(field);
  170. }
  171.  
  172. table.FieldList = fieldList;
  173.  
  174. return table;
  175.  
  176. }
  177.  
  178. private List<MTableIndex> GetIndexInfo(System.Data.IDbConnection conn)
  179. {
  180. string sql = @"SELECT
  181. TableId=O.[object_id],
  182. TableName=O.Name,
  183. IndexId=ISNULL(KC.[object_id],IDX.index_id),
  184. IndexName=IDX.Name,
  185. IndexType=ISNULL(KC.type_desc,''),
  186. Index_Column_id=IDXC.index_column_id,
  187. ColumnID=C.Column_id,
  188. ColumnName=C.Name,
  189. Sort=CASE INDEXKEY_PROPERTY(IDXC.[object_id],IDXC.index_id,IDXC.index_column_id,'IsDescending')
  190. WHEN 1 THEN 'DESC' WHEN 0 THEN 'ASC' ELSE '' END,
  191. PrimaryKey=IDX.is_primary_key,
  192. IsUnique=IDX.is_unique,
  193. Ignore_dup_key=IDX.ignore_dup_key,
  194. Disabled=IDX.is_disabled,
  195. Fill_factor=IDX.fill_factor,
  196. Padded=IDX.is_padded
  197. FROM sys.indexes IDX
  198. INNER JOIN sys.index_columns IDXC
  199. ON IDX.[object_id]=IDXC.[object_id]
  200. AND IDX.index_id=IDXC.index_id
  201. LEFT JOIN sys.key_constraints KC
  202. ON IDX.[object_id]=KC.[parent_object_id]
  203. AND IDX.index_id=KC.unique_index_id
  204. INNER JOIN sys.objects O
  205. ON O.[object_id]=IDX.[object_id]
  206. INNER JOIN sys.columns C
  207. ON O.[object_id]=C.[object_id]
  208. AND O.type='U'
  209. AND O.is_ms_shipped=0
  210. AND IDXC.Column_id=C.Column_id
  211. WHERE IDX.is_primary_key<>1
  212. AND O.Name NOT LIKE 'sys%';";
  213.  
  214. SqlCommand comm = new SqlCommand(sql, (SqlConnection)conn);
  215. SqlDataReader reader = comm.ExecuteReader();
  216. List<MTableIndex> list = new List<MTableIndex>();
  217. while (reader.Read())
  218. {
  219. MTableIndex model = new MTableIndex();
  220. model.TableName = DBUtil.GetDBValueStr(reader, "TableName");
  221. model.IndexType = DBUtil.GetDBValueStr(reader, "IndexType");
  222. model.IndexName = DBUtil.GetDBValueStr(reader, "IndexName");
  223. model.ColumnName = DBUtil.GetDBValueStr(reader, "ColumnName");
  224. model.IsUnique = DBUtil.GetDBValueBool(reader, "IsUnique");
  225. model.Sort = DBUtil.GetDBValueStr(reader, "Sort");
  226.  
  227. list.Add(model);
  228. }
  229.  
  230. return list;
  231. }
  232. }
  233. }

4 生成文档结果

读取数据库信息并生成表设计文档Word版本的更多相关文章

  1. sqlserver生成表结构文档的方法

    只说原理了,具体 可以自己使用程序去生成htm或word文档. 1.首先获取所有的表 SELECT name, id From sysobjects WHERE xtype = 'u' ORDER B ...

  2. 数据库表结构文档查看器 基于netcore

    前言 日常开发业务代码,新接手一块不熟悉的业务时需要频繁的查看对应业务的数据库表设计文档.相比于直接翻看业务代码,有必要提供一个数据库表结构文档查看器来解决这些繁琐的问题. CML.SqlDoc CM ...

  3. Access数据库自动生成设计文档

    在做Access数据库设计时,常常直接在access文件中建表,建字段,然后写设计文档时,又得重新再写一遍字段和表间关系.其实access数据库自己就支持自动生成数据库文档. 操作方法如下: 数据库工 ...

  4. 【工具篇】利用DBExportDoc V1.0 For MySQL自动生成数据库表结构文档

    对于DBA或开发来说,如何规范化你的数据库表结构文档是灰常之重要的一件事情.但是当你的库,你的表排山倒海滴多的时候,你就会很头疼了. 推荐一款工具DBExportDoc V1.0 For MySQL( ...

  5. 利用DBExportDoc V1.0 For MySQL自动生成数据库表结构文档

    对于DBA或开发来说,如何规范化你的数据库表结构文档是灰常之重要的一件事情.但是当你的库,你的表排山倒海滴多的时候,你就会很头疼了. 推荐一款工具DBExportDoc V1.0 For MySQL( ...

  6. php-生成数据库设计文档

    在线以及提供下载数据库设计文档 $dbserver = "192.168.128.190:42578"; $dbusername = "root"; $dbpa ...

  7. 有问必答项目 -数据库设计文档(ask-utf-8)

    有问必答项目 -数据库设计文档(ask-utf-8) 表前缀的使用 早期租用公共的服务器 一个数据库,保存多个项目(问答.电子商务.医院),为了区分这些项目,使用前缀分割 ask_ ec_ hospi ...

  8. Gemini.Workflow 双子工作流高级教程:数据库-设计文档

    数据库设计文档 数据库名:Workflow_New 序号 表名 说明 1 WF_Activity wf_Activity 2 WF_ActivityInstance wf_ActivityInstan ...

  9. Net 通用权限管理系统源码 带数据库设计文档,部署说明文档

    Net 通用权限管理系统源码 带数据库设计文档,部署说明文档 包括数据库设计文档部署安装文档源码数据库文件 下载地址:http://www.mallhd.com/archives/1389

随机推荐

  1. Android自动化测试中AccessibilityService获取控件信息(2)-三种方式对比

    Android自动化测试中AccessibilityService获取控件信息(2)-三种方式对比   上一篇文章: Android自动化测试中AccessibilityService获取控件信息(1 ...

  2. request笔记记录

    1.https请求报错解决方法,添加verify=False参数 r = requests.get(json=payload, headers=headers,verify=False) 1)由于这里 ...

  3. JavaScript-Tool:Numeral.js

    ylbtech-JavaScript-Tool:Numeral.js A javascript library for formatting and manipulating numbers. 1. ...

  4. C++中关于class B:A与Class B::A问题

    一,class B:A为类的继承关系,即A类是B类的基类class <派生类名>:<继承方式><基类名>{<派生类新定义成员>}; 例如: #inclu ...

  5. 模型融合策略voting、averaging、stacking

    原文:https://zhuanlan.zhihu.com/p/25836678 1.voting 对于分类问题,采用多个基础模型,采用投票策略选择投票最多的为最终的分类. 2.averaging 对 ...

  6. IO基础知识

    传统的IO是阻塞的,BIO----基于流的模式,数据与Stream直接通信 NIO非阻塞的基于快的模式.数据与channel不直接交换数据,而是通过buffer进行数据交换. 基于文件的IO 基于网络 ...

  7. ExtJS模版技术

    学习ExtJS一段时间以后,大家基本都会对于一些显示数据的组件不太符合需求,可能自己需要的组件在ExtJS里面不存在,这是大家基本就会使用Html属性,直接使用Html进行绘制页面数据展现. 但是,使 ...

  8. php字符串类型讲解

    PHP 支持八种原始类型(type). 四种标量类型: string(字符串) integer(整型) float(浮点型,也作 double ) boolean(布尔型) 两种复合类型: array ...

  9. 开发组件:Systemd

    Systemd 入门教程:命令篇 http://www.ruanyifeng.com/blog/2016/03/systemd-tutorial-commands.html

  10. python拓展4 数据结构

    内容: 1.数组 2.链表 3.字典 4.二叉树(搜索树) 5.set集合实现 1.数组 数组在python中是以列表的形式存在,基本上每一个语言中都有数组形式的数据结构存在 数组一般存储在连续的一块 ...