將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; }
}
}

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