using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System;
using System.Data.SqlClient;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
namespace Mothersys.WebForms.aspx.tools
{
public class DatabaseDocumentGenerator
{
// 生成数据库字典的Word文档
public static void GenerateDatabaseDictionary(string connectionString, string wordFilePath)
{
// 创建Word文档
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(wordFilePath, WordprocessingDocumentType.Document))
{
// 添加主文档部件
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
mainPart.Document = new Document(new Body());
// 设置文档字体和样式
StyleDefinitionsPart stylePart = mainPart.AddNewPart<StyleDefinitionsPart>();
stylePart.Styles = new Styles();
AddStyles(stylePart);
// 获取数据库的表信息
string query = @"
SELECT
t.name AS TableName,
c.name AS ColumnName,
ty.name AS DataType,
c.max_length AS MaxLength,
c.precision AS Precision,
c.scale AS Scale,
c.is_nullable AS IsNullable,
ep.value AS ColumnComment
FROM sys.tables t
INNER JOIN sys.columns c ON t.object_id = c.object_id
INNER JOIN sys.types ty ON c.user_type_id = ty.user_type_id
LEFT JOIN sys.extended_properties ep
ON ep.major_id = c.object_id AND ep.minor_id = c.column_id
ORDER BY t.name, c.column_id;";
// 执行查询并将结果写入Word文档
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader = command.ExecuteReader();
string currentTable = string.Empty;
Table table = null;
while (reader.Read())
{
string tableName = reader["TableName"].ToString();
string columnName = reader["ColumnName"].ToString();
string dataType = reader["DataType"].ToString();
object maxLengthObj = reader["MaxLength"];
object precisionObj = reader["Precision"];
object scaleObj = reader["Scale"];
bool isNullable = (bool)reader["IsNullable"];
string columnComment = reader["ColumnComment"] as string ?? "无";
// 替换字段说明中的 "Candidate" 为 "Applicant"
columnComment = columnComment.Replace("Candidate", "Applicant");
// 处理 maxLength、precision 和 scale
int maxLength = (maxLengthObj != DBNull.Value) ? Convert.ToInt32(maxLengthObj) : 0;
int precision = (precisionObj != DBNull.Value) ? Convert.ToInt32(precisionObj) : 0;
int scale = (scaleObj != DBNull.Value) ? Convert.ToInt32(scaleObj) : 0;
// 新表开始时创建表格
if (currentTable != tableName)
{
if (table != null)
{
// 如果当前表已经有内容,结束上一个表格并继续
mainPart.Document.Body.Append(table);
}
// 表名设置为二级标题,无边框
Paragraph tableNamePara = new Paragraph(new ParagraphProperties(new ParagraphStyleId() { Val = "Heading2" }));
tableNamePara.Append(new Run(new Text($"表名: {tableName}")));
mainPart.Document.Body.Append(tableNamePara);
// 创建新的表格
table = new Table();
// 设置表格边框和宽度为100%
TableProperties tableProperties = new TableProperties(
new TableWidth() { Type = TableWidthUnitValues.Auto, Width = "5000" }, // 设置表格宽度为100%
new TableBorders(
new TopBorder() { Val = BorderValues.Single, Size = 4, Space = 0, Color = "A9A9A9" }, // 灰色边框
new BottomBorder() { Val = BorderValues.Single, Size = 4, Space = 0, Color = "A9A9A9" },
new LeftBorder() { Val = BorderValues.Single, Size = 4, Space = 0, Color = "A9A9A9" },
new RightBorder() { Val = BorderValues.Single, Size = 4, Space = 0, Color = "A9A9A9" },
new InsideHorizontalBorder() { Val = BorderValues.Single, Size = 4, Space = 0, Color = "A9A9A9" },
new InsideVerticalBorder() { Val = BorderValues.Single, Size = 4, Space = 0, Color = "A9A9A9" }
)
);
table.Append(tableProperties);
// 添加表格头并设置为灰色背景
TableRow headerRow = new TableRow();
AddTableCell(headerRow, "列名", true); // 设置灰色背景
AddTableCell(headerRow, "数据类型", true);
AddTableCell(headerRow, "最大长度", true);
AddTableCell(headerRow, "精度", true);
AddTableCell(headerRow, "小数位数", true);
AddTableCell(headerRow, "是否允许空值", true);
AddTableCell(headerRow, "字段说明", true);
table.Append(headerRow);
currentTable = tableName;
}
// 为当前表添加数据行
TableRow row = new TableRow();
AddTableCell(row, columnName, false);
AddTableCell(row, dataType, false);
AddTableCell(row, maxLength.ToString(), false);
AddTableCell(row, precision.ToString(), false);
AddTableCell(row, scale.ToString(), false);
AddTableCell(row, isNullable ? "是" : "否", false);
AddTableCell(row, columnComment, false);
table.Append(row);
}
// 最后一张表格需要追加
if (table != null)
{
mainPart.Document.Body.Append(table);
}
reader.Close();
}
}
Console.WriteLine($"数据库字典文档已生成:{wordFilePath}");
}
// 添加带灰色背景的单元格
private static void AddTableCell(TableRow row, string text, bool isHeader)
{
TableCell cell = new TableCell();
if (isHeader)
{
cell.Append(new TableCellProperties(
new Shading() { Val = ShadingPatternValues.Clear, Fill = "D3D3D3" })); // 设置灰色背景
}
cell.Append(new Paragraph(new Run(new Text(text))));
row.Append(cell);
}
// 添加样式
private static void AddStyles(StyleDefinitionsPart stylePart)
{
Styles styles = stylePart.Styles;
// 添加段落样式:二级标题
Style heading2Style = new Style()
{
Type = StyleValues.Paragraph,
StyleId = "Heading2",
Default = true
};
heading2Style.Append(new Name() { Val = "Heading 2" }); // 设置样式名称
heading2Style.Append(new ParagraphProperties(
new Justification() { Val = JustificationValues.Center }, // 居中对齐
new SpacingBetweenLines() { After = "120" } // 设置段落之后的间距
));
styles.Append(heading2Style);
// 添加表格样式
Style tableStyle = new Style()
{
Type = StyleValues.Table,
StyleId = "TableStyle",
Default = true,
StyleName = new StyleName() { Val = "Table Style" },
BasedOn = new BasedOn() { Val = "Normal" }
};
tableStyle.Append(new TableProperties(new TableStyle() { Val = "TableGrid" }));
styles.Append(tableStyle);
}
}
}