将C#中的DataTable转换为Word表格

using Microsoft.Office.Interop.Word;
using System.Data;

namespace DataTableToWord
{
class Program
{
static void Main(string[] args)
{
// 创建Word应用程序对象
Application app = new Application();
// 创建一个新的文档
Document doc = app.Documents.Add();

// 在文档中插入表格
Range range = doc.Range();
Table table = doc.Tables.Add(range, DataTable.Rows.Count + 1, DataTable.Columns.Count, WdDefaultTableBehavior.wdWord9TableBehavior);

// 将列标题写入表格
for (int i = 0; i < DataTable.Columns.Count; i++)
{
table.Cell(1, i + 1).Range.Text = DataTable.Columns[i].ColumnName;
}

// 填充表格单元格内容
for (int i = 0; i < DataTable.Rows.Count; i++)
{
for (int j = 0; j < DataTable.Columns.Count; j++)
{
table.Cell(i + 2, j + 1).Range.Text = DataTable.Rows[i][j].ToString();
}
}

// 调整表格样式和格式
table.PreferredWidthType = WdPreferredWidthType.wdPreferredWidthPercent;
table.PreferredWidth = 100f;
table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
table.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;

// 保存Word文档
doc.SaveAs2(@"C:\Users\UserName\Documents\Table.docx");
doc.Close();
app.Quit();
}

static DataTable DataTable { get; set; }
}
}

posted @ 2023-04-29 09:36  刘崇军  阅读(186)  评论(0编辑  收藏  举报