4
for (var i = 0; i <= data.GetUpperBound(0); i++)
{
    var tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
    for (var j = 0; j <= data.GetUpperBound(1); j++)
    {
        var tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell();

        tc.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data[i, j]))));


        tr.Append(tc);

    }
    table.Append(tr);
}

I want to change fontsize in table cell. Can you help me with that? I don't know why they didn't add a property for cell fontsize.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ben V.
  • 43
  • 1
  • 1
  • 6

1 Answers1

11

To change the fontsize of a table cell, you need to add a RunProperties to the Run. The fontsize is specified inside a FontSize element inside that RunProperties.

For example to change all of your entries to fontsize 18, your code would look like:

for (var i = 0; i <= data.GetUpperBound(0); i++)
{
    var tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
    for (var j = 0; j <= data.GetUpperBound(1); j++)
    {
        var tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell();

        var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
        var run = new DocumentFormat.OpenXml.Wordprocessing.Run();
        var text = new DocumentFormat.OpenXml.Wordprocessing.Text(data[i, j]);

        // your old code for reference:  tc.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data[i, j]))));

        RunProperties runProperties1 = new RunProperties();
        FontSize fontSize1 = new FontSize(){ Val = "36" };
        runProperties1.Append(fontSize1);

        run.Append(runProperties1);
        run.Append(text);

        paragraph.Append(run);
        tc.Append(paragraph);

        tr.Append(tc);

    }
    table.Append(tr);
}
Taterhead
  • 5,763
  • 4
  • 31
  • 40
  • Wow. I saw a lot of pages with that code, but didnt know, that it will works for me too. thank you very much. – Ben V. Jul 07 '17 at 09:19
  • now i tried to change the font with RunFonts fonts = new RunFonts(); fonts.Ascii = "Arial"; fonts.HighAnsi = "Arial"; runProperties1.Append(fonts); and nothing happened... – Ben V. Jul 07 '17 at 12:57
  • 1
    you should check out the OpenXML productivity tool - https://stackoverflow.com/documentation/openxml/6967/getting-started-with-openxml/28257/using-open-xml-sdk-2-5-productivity-tool . Create the document how you want it and reverse engineer it with this tool and it will tell you the correct code to use to get your desired font. – Taterhead Jul 07 '17 at 13:17
  • 1
    Is there any way to set the font size if the cell is empty? See my [question](https://stackoverflow.com/questions/51536259/how-to-set-font-size-in-empty-cell-in-openxml-word-table) – Little geek Jul 26 '18 at 10:34