C# 使用 Open XML SDK 製作 Word 表格

書接上回, C# 使用 Open XML SDK 2.5 輸出 Word 文件 已經有基本的操作了,本篇就來畫表格吧。

首先複習一下最基礎的產生 word:
    
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;


string filepath = @"./test.docx";
using var wordDocument = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document);

MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());

// todo:

wordDocument.Close();
Console.WriteLine("Hello World!");
    

之後程式碼就是放在上面 todo 的位置

基本表格

    
var table = new Table();
body.Append(table);

var row = new TableRow();
table.Append(row);

var cell1 = new TableCell(new Paragraph(new Run(new Text("儲存格 1"))));
var cell2 = new TableCell(new Paragraph(new Run(new Text("儲存格 2"))));

row.Append(cell1);
row.Append(cell2);
    

在這裡顯示文字還是需要包在 Paragraph > Run > Text 中。

表格樣式

預設框線:
    
tableProperties.TableBorders = new TableBorders();
tableProperties.TableBorders.TopBorder = new TopBorder() { Val = BorderValues.Single, Size = 4, Space = 0 };
tableProperties.TableBorders.BottomBorder = new BottomBorder() { Val = BorderValues.Single, Size = 4, Space = 0 };
tableProperties.TableBorders.LeftBorder = new LeftBorder() { Val = BorderValues.Single, Size = 4, Space = 0 };
tableProperties.TableBorders.RightBorder = new RightBorder() { Val = BorderValues.Single, Size = 4, Space = 0 };
tableProperties.TableBorders.InsideHorizontalBorder = new InsideHorizontalBorder() { Val = BorderValues.Single, Size = 4, Space = 0 };
tableProperties.TableBorders.InsideVerticalBorder = new InsideVerticalBorder() { Val = BorderValues.Single, Size = 4, Space = 0 };
    



註: 要在 table.Append(row); 之前就要 table.AppendChild(tableProperties); ,不然會看不到表格樣式,但是可以在後面再調整 tableProperties 。

表格寬度

表格寬度其實是要看儲存格的寬度,下面是設定兩格儲存格寬度各 50 %,佔滿整頁(到左右邊界,並非到最左右側)
    
cell1.TableCellProperties = new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Pct, Width = "50" });
cell2.TableCellProperties = new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Pct, Width = "50" });
    


底色(網底、背景色)

    
cell1.TableCellProperties.Shading = new Shading() { Fill = "FF6600" };
    


不過這樣中間的框線就被蓋掉了...

儲存格邊框

儲存格右側邊框
    
cell1.TableCellProperties.AppendChild(new RightBorder() { Val = BorderValues.Single, Size = 4, Space = 0 });
    




參考資料:
GitHub dotnet/Open-XML-SDK - Open XML SDK 2.5 Productivity Tool

留言