27

How can I change the font family of the document via OpenXml ? I tried some ways but, when I open the document, it's always in Calibri

Follow my code, and what I tried.

The Header Builder I think is useless to post

private static void BuildDocument(string fileName, List<string> 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<HeaderPart>();
        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();
    }             
}
Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
Lucas_Santos
  • 4,638
  • 17
  • 71
  • 118

2 Answers2

45

In order to style your text with a specific font follow the steps listed below:

  1. Create an instance of the RunProperties class.
  2. Create an instance of the RunFont class. Set the Ascii property to the desired font familiy.
  3. Specify the size of your font (half-point font size) using the FontSize class.
  4. Prepend the RunProperties instance to your run containing the text to style.

Here is a small code example illustrating the steps described above:

private static void BuildDocument(string fileName, List<string> 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();
    }
}

Hope, this helps.

Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
Hans
  • 12,902
  • 2
  • 57
  • 60
  • 9
    When you create documents with non-ascii characters you need to set additional properties on the `RunFonts` instance. For example if you want to set the font of a text with German umlauts you need to change the `HighAnsi` property to your font (e.g. "Arial") as well. – Chaquotay Jun 01 '15 at 07:20
0

If you are using Stylesheet just add an instance of FontName property at appropriate font index during Fonts initilaization.

    private Stylesheet GenerateStylesheet()
    {
        Stylesheet styleSheet = null;

        Fonts fonts = new Fonts(
            new Font( // Index 0 - default
                new FontSize() { Val = 8 },
                new FontName() { Val = "Arial"} //i.e. or any other font name as string
            );

        Fills fills = new Fills( new Fill(new PatternFill() { PatternType = PatternValues.None }));

        Borders borders = new Borders( new Border() );

        CellFormats cellFormats = new CellFormats( new CellFormat () );

        styleSheet = new Stylesheet(fonts, fills, borders, cellFormats);

        return styleSheet;
    }

Then use it in Workbook style part as below.

WorkbookStylesPart stylePart = workbookPart.AddNewPart<WorkbookStylesPart>();
stylePart.Stylesheet = GenerateStylesheet();
stylePart.Stylesheet.Save();
  • The question was for Word; I think your answer is for Excel. – james.garriss Jun 14 '21 at 18:55
  • Hello james.garriss, do you might not have tried my answer. Just based on your guess downvoting someone's answer is very bad practice. Although some guys like you made the stack overflow platform uncomfortable for newcomers. Please try to avoid misusing your downvote power. – Shafiqul Islam Jun 16 '21 at 05:06
  • If you answer the question well, you get upvoted. If you don't, you get downvoted. That's how SO works. Attacking me won't help. Maybe you could just update your answer to work for Word. – james.garriss Jun 18 '21 at 12:27