表格OpenXML C#中的格式字体

时间:2013-02-28 16:52:38

标签: c# openxml

我想使用OpenXML WordProcessing创建表。我想格式化单元格内的字体。这是我的代码

MainDocumentPart mainDocumentPart = doc.AddMainDocumentPart();
mainDocumentPart.Document = new Document();
Body body = mainDocumentPart.Document.AppendChild(new Body());

RunProperties runHeader = new RunProperties();
RunFonts runFont = new RunFonts();
runFont.Ascii = "Lucida Sans";
runHeader.Append(runFont);                    
runHeader.Append(new Bold());
runHeader.Append(new FontSize() { Val = "16" }); 

//// Create a new table
Table tbl = new Table();

tr = new TableRow();
tc = new TableCell();

Paragraph paraHeader = new Paragraph();
Text heading_text = new Text("Company Name");
runHeader.Append(heading_text);
paraHeader.Append(runHeader);
tc.Append(paraHeader);
tr.Append(tc);
tbl.Append(tr);

body.AppendChild(tbl);

但是当我打开Microsoft Word时,我收到了错误。它说文件内容有问题

2 个答案:

答案 0 :(得分:2)

您要将文本附加到“运行属性”,它需要附加到“运行”。 尝试:

Text heading_text = new Text("Company Name");

////create the run
Run runHeaderRun = new Run();

////append the run properties and text to the run
runHeaderRun.Append(runHeader);
runHeaderRun.Append(heading_text);

////append the run to the paragraph
paraHeader.Append(runHeaderRun);

tc.Append(paraHeader);

答案 1 :(得分:0)

RunProperties rp = new RunProperties();
RunFonts runFont = new RunFonts() { Ascii = "Calibri Light" };
rp.Append(runFont);
rp.Append(new Color() { Val = "#2E74B5" });

body.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new Run(rp, new Text("3. Risk Assessment"))));

使用非常简单,试试这个。