对单词应用 Table 样式 Table
Apply a TableStyle to a Word Table
尝试使用预定义样式设置 table 样式,但没有任何效果。我尝试过使用一个新创建的文档和一个从保存的模板创建的文档。使用 SDK Productivity 工具,我可以看到样式存在于模板中,但未应用。我试过附加样式或直接设置它,但似乎都不起作用。
public static void CreateWordprocessingDocument(string fileName) {
string[,] data = {
{"Texas", "TX"},
{"California", "CA"},
{"New York", "NY"},
{"Massachusetts", "MA"}
};
using (var wordDocument = WordprocessingDocument.Open(fileName, true)) {
// We need to change the file type from template to document.
wordDocument.ChangeDocumentType(WordprocessingDocumentType.Document);
var body = wordDocument.GetDocument().Body;
Table table = new Table();
TableProperties props = new TableProperties();
TableStyle tableStyle = new TableStyle { Val = "Light Shading Accent 1" };
props.TableStyle = tableStyle;
//props.Append(tableStyle);
table.AppendChild(props);
for (var i = 0; i <= data.GetUpperBound(0); i++) {
var tr = new TableRow();
for (var j = 0; j <= data.GetUpperBound(1); j++) {
var tc = new TableCell();
tc.Append(new Paragraph(new Run(new Text(data[i, j]))));
tc.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto }));
tr.Append(tc);
}
table.Append(tr);
}
body.Append(table);
wordDocument.GetDocument().Save();
}
}
终于想通了。我使用的是样式名称而不是样式 ID。所以声明样式的行应该如下所示:
TableStyle tableStyle = new TableStyle { Val = "LightShading-Accent1" };
尝试使用预定义样式设置 table 样式,但没有任何效果。我尝试过使用一个新创建的文档和一个从保存的模板创建的文档。使用 SDK Productivity 工具,我可以看到样式存在于模板中,但未应用。我试过附加样式或直接设置它,但似乎都不起作用。
public static void CreateWordprocessingDocument(string fileName) {
string[,] data = {
{"Texas", "TX"},
{"California", "CA"},
{"New York", "NY"},
{"Massachusetts", "MA"}
};
using (var wordDocument = WordprocessingDocument.Open(fileName, true)) {
// We need to change the file type from template to document.
wordDocument.ChangeDocumentType(WordprocessingDocumentType.Document);
var body = wordDocument.GetDocument().Body;
Table table = new Table();
TableProperties props = new TableProperties();
TableStyle tableStyle = new TableStyle { Val = "Light Shading Accent 1" };
props.TableStyle = tableStyle;
//props.Append(tableStyle);
table.AppendChild(props);
for (var i = 0; i <= data.GetUpperBound(0); i++) {
var tr = new TableRow();
for (var j = 0; j <= data.GetUpperBound(1); j++) {
var tc = new TableCell();
tc.Append(new Paragraph(new Run(new Text(data[i, j]))));
tc.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto }));
tr.Append(tc);
}
table.Append(tr);
}
body.Append(table);
wordDocument.GetDocument().Save();
}
}
终于想通了。我使用的是样式名称而不是样式 ID。所以声明样式的行应该如下所示:
TableStyle tableStyle = new TableStyle { Val = "LightShading-Accent1" };