C# 将表样式应用于Word表
尝试使用预定义样式设置表格样式,但没有任何效果。我尝试了一个新创建的文档和一个从保存的模板创建的文档。使用SDK生产力工具,我可以看到样式在模板中,但它没有被应用。我尝试过添加样式或直接设置,但两者似乎都不起作用C# 将表样式应用于Word表,c#,ms-word,openxml,docx,C#,Ms Word,Openxml,Docx,尝试使用预定义样式设置表格样式,但没有任何效果。我尝试了一个新创建的文档和一个从保存的模板创建的文档。使用SDK生产力工具,我可以看到样式在模板中,但它没有被应用。我尝试过添加样式或直接设置,但两者似乎都不起作用 public static void CreateWordprocessingDocument(string fileName) { string[,] data = { {"Texas", "TX"}, {"C
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();
}
}
公共静态void CreateWordprocessingDocument(字符串文件名){
字符串[,]数据={
{“德克萨斯州”、“德克萨斯州”},
{“加利福尼亚州”、“加利福尼亚州”},
{“纽约”,“纽约”},
{“马萨诸塞州”、“马萨诸塞州”}
};
使用(var wordDocument=WordprocessingDocument.Open(fileName,true)){
//我们需要将文件类型从模板更改为文档。
wordDocument.ChangeDocumentType(WordprocessingDocumentType.Document);
var body=wordDocument.GetDocument().body;
Table Table=新表();
TableProperties props=新的TableProperties();
TableStyle TableStyle=新TableStyle{Val=“浅色着色强调1”};
props.TableStyle=表样式;
//附加(表样式);
表.儿童(道具);
对于(var i=0;i最终解决了这个问题。我使用的是样式名称,而不是样式id。因此声明样式的行应该如下所示:
TableStyle tableStyle = new TableStyle { Val = "LightShading-Accent1" };
终于明白了。我使用的是样式名称,而不是样式id。因此声明样式的行应该如下所示:
TableStyle tableStyle = new TableStyle { Val = "LightShading-Accent1" };
除了这一行之外,我有完全相同的代码。不确定这是否会产生差异。table.AppendChild(tPr);强制转换不应该产生差异(只是测试以确认)。您的表是否具有样式?是的,它们具有样式。我也可以手动将样式应用于表。我可以应用大多数属性(如边框、颜色等)手动操作也很好。但是我创建了很多表,并且希望能够使用预定义的样式来简化代码并使其更易于更改。使用生产工具,您在xml文件中看到了什么?我看到了类似于……的内容,除了这一行之外,我有完全相同的代码。不确定这是否会产生影响difference.table.AppendChild(tPr);强制转换不应该造成差异(只是测试以确认)。您的表是否显示样式?是的,它们显示样式。我也可以手动将样式应用于表。我可以应用大多数属性(如边框、颜色等)手动操作也很好。但是我创建了很多表,并且希望能够使用预定义的样式来简化代码并允许更轻松地更改。使用生产工具,您在xml文件中看到了什么?我看到了类似于。。。。