尝试使用预定义样式设置表格样式,但没有任何效果。我尝试过使用新创建的文档和从保存的模板创建的文档。使用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();
}
}
答案 0 :(得分:2)
终于明白了。我使用的是样式名称,而不是样式ID。因此声明样式的行应该如下所示:
TableStyle tableStyle = new TableStyle { Val = "LightShading-Accent1" };