如何更改字体打开xml

如何通过OpenXml更改文档的字体系列? 我尝试了一些方法但是,当我打开文档时,它总是在Calibri中

按照我的代码,我尝试了。

我认为Header Builder无用于发布

private static void BuildDocument(string fileName, List lista, string tipo) { using (var w = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document)) { var mp = w.AddMainDocumentPart(); var d = new DocumentFormat.OpenXml.Wordprocessing.Document(); var b = new Body(); var p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(); var r = new Run(); // Get and format the text. for (int i = 0; i < lista.Count; i++) { Text t = new Text(); t.Text = lista[i]; if (t.Text == " ") { r.Append(new CarriageReturn()); } else { r.Append(t); r.Append(new CarriageReturn()); } } // What I tried var rPr = new RunProperties(new RunFonts() { Ascii = "Arial" }); lista.Clear(); p.Append(r); b.Append(p); var hp = mp.AddNewPart(); string headerRelationshipID = mp.GetIdOfPart(hp); var sectPr = new SectionProperties(); var headerReference = new HeaderReference(); headerReference.Id = headerRelationshipID; headerReference.Type = HeaderFooterValues.Default; sectPr.Append(headerReference); b.Append(sectPr); d.Append(b); // Customize the header. if (tipo == "alugar") { hp.Header = BuildHeader(hp, "Anúncio Aluguel de Imóvel"); } else if (tipo == "vender") { hp.Header = BuildHeader(hp, "Anúncio Venda de Imóvel"); } else { hp.Header = BuildHeader(hp, "Aluguel/Venda de Imóvel"); } hp.Header.Save(); mp.Document = d; mp.Document.Save(); w.Close(); } } 

要使用特定字体设置文本样式,请按照下面列出的步骤操作:

  1. 创建RunProperties类的实例。
  2. 创建RunFont类的实例。 将Ascii属性设置为所需的字体系列。
  3. 使用FontSize类指定字体大小(半点字体大小)。
  4. 将RunProperties实例添加到包含要设置样式的文本的运行中。

这是一个小代码示例,说明了上述步骤:

 private static void BuildDocument(string fileName, List text) { using (var wordDoc = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document)) { var mainPart = wordDoc.AddMainDocumentPart(); mainPart.Document = new Document(); var run = new Run(); foreach (string currText in text) { run.AppendChild(new Text(currText)); run.AppendChild(new CarriageReturn()); } var paragraph = new Paragraph(run); var body = new Body(paragraph); mainPart.Document.Append(body); var runProp = new RunProperties(); var runFont = new RunFonts { Ascii = "Arial" }; // 48 half-point font size var size = new FontSize { Val = new StringValue("48") }; runProp.Append(runFont); runProp.Append(size); run.PrependChild(runProp); mainPart.Document.Save(); wordDoc.Close(); } } 

希望这可以帮助。