3

I need to change the font style (font type ) of some cells in Excel sheet. Excel sheet is generated by Microsoft.Office.Interop.Excel

I want to change B3 to B100 range to be in Arial font type. here is my code

Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

app.Visible = true;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from gridview";
worksheet.get_Range("B3", "B100").Cells.Font.FontStyle = "Arial";

for (int i = 1; i < records_datagridview.Columns.Count + 1; i++)
{
   worksheet.Cells[1, i] = records_datagridview.Columns[i - 1].HeaderText;
}

for (int i = 0; i < records_datagridview.Rows.Count; i++)
{
   for (int j = 0; j < records_datagridview.Columns.Count; j++)
   {
      worksheet.Cells[i + 2, j + 1] = records_datagridview.Rows[i].Cells[j].Value.ToString();
   }
}

String file_path = fbd.SelectedPath + "/records_sheet_" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "_.xlsx";

workbook.SaveAs(file_path, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing);

app.Quit();

I used

worksheet.get_Range("B3", "B4").Cells.Font.FontStyle = "Arial";

But it's not working Can any one help me on this

Jimi
  • 29,621
  • 8
  • 43
  • 61
Achira Shamal
  • 527
  • 1
  • 5
  • 18
  • "But it's not working" is a horrible way to describe or better yet to not describe what is happening. Use worksheet.get_Range("B3", "B4").Cells.Font.Name = "Arial"; – Sorceri Dec 09 '17 at 17:36

2 Answers2

4

hange your code to this:

worksheet.get_Range("B3", "B4").Cells.Font.Name = "Arial";

Tip: In many cases, you can answer questions like these yourself: simply record an Excel macro and look at the generated code. Even though it is VBA, not C#, you will often see what you need.

Heinz Kessler
  • 1,610
  • 11
  • 24
1

You need to define style first.

Excel.Style style = workbook.Styles.Add("NewStyle");
style.Font.Name = "Arial";

Then you need to define cell range and apply new style.

Excel.Range rangeStyles = app.get_Range("B3", "B100");
rangeStyles.Style = "NewStyle";

For more info, check out Microsoft documentatation page https://msdn.microsoft.com/en-us/library/f1hh9fza.aspx