Home » excel » How to use fonts having space in C# windows form to create excel workseet?

How to use fonts having space in C# windows form to create excel workseet?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am using an IEnumerable variable to create an Excel worksheet in C# windows form application. The problem is that I can set created worksheet font if the font name has 1 word, ex. ‘IRNazanin’, but for font name with space it doesn’t work, ex. ‘B Mitra’. My code is:

var wb = new XLWorkbook { RightToLeft = true };
var ws = wb.Worksheets.Add("Sick_Information");
ws.Columns().AdjustToContents();
ws.Style.Font.FontName = "B Mitra";

I have tried using font name:

  • without spase, ex. “BMitra”
  • with a hyphen, ex. “B-Mitra”
  • with underline, ex. “B_Mitra”
  • with extra single qout, ex. “‘B Mitra'”

Still not working.
I am using ClosedXML.Excel library with ClosedXML version 0.94.2.0 and MS Office 2016. The excel will get the font name but won’t apply it.

enter image description here

True B Mitra font is like this. (Changed manually)

enter image description here

The customer needs file with B Mitra font and Persian numbers. So I have no choice to change the font.

How to&Answers:

"B Mitra" is a valid font name, but you also need to change FontCharSet:

cell.Style.Font.SetFontName("B Mitra");
cell.Style.Font.SetFontCharSet(XLFontCharSet.Arabic);

ClosedXML uses XLFontCharSet.Default by default. Output Excel file shows correct font name, but doesn’t display cell content properly:

font

I used Open XML SDK 2.5 Productivity Tool for Microsoft Office to inspect Excel file. With XLFontCharSet.Arabic there is a line there:

FontCharSet fontCharSet6 = new FontCharSet(){ Val = 178 };

And content is displayed as expected.

Answer:

If you are using ClosedXML library then try use setFontName method:

ws.Style.Font.SetFontName("B Mitra");