Search code examples
c#automationexport-to-excelexcel-interop

Microsoft.Office.Interop.Excel.Worksheet.Cells[x,y].Style?


I found some code which uses Style property of Microsoft.Office.Interop.Excel.Worksheet.Cells[x,y] but it is treated as an object in my Visual Studo code editor:

Workbook wb = new Application.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet ws = wb.Sheets[1];
ws.Cells[x,y] is simply treated as an object so how can I use its Style property?

I'm using Microsoft Excel 15.0 Objects Library (goes with Microsoft Office 2013). Does that matter?

Could you please explain this to me? Thank you.


Solution

  • you have to cast the object as a Range.

    The Range interface/object contains all the style and value information for the cell or range that you are specifying.

    some examples:

    ((Excel.Range)ws.Cells[r, c]).NumberFormat = format;
    ((Excel.Range)ws.Cells[r, c]).Value2 = cellVal;
    ((Excel.Range)ws.Cells[r, c]).Interior.Color = ColorTranslator.ToOle(Color.Red);
    ((Excel.Range)ws.Cells[r, c]).Style.Name = "Normal"
    

    etc etc and so on.

    Have a link: https://learn.microsoft.com/en-us/office/vba/api/Excel.Range.Style