Simple way to access to Excel cell by its "coordination" eg "B7" instead of [7,1]

76 Views Asked by At

I have Excel file in which I want to fill data. The cells may be re-arranged and will be given in a list in format like "B7", "C5", "G8", etc...

So I would like to access the sheet by these coordinations.

I have this code:

Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;

try
{
    //Start Excel and get Application object.
    oXL = new Excel.Application();
    oXL.Visible = false;

    //Open existing workbook
    oWB = oXL.Workbooks.Open(filename);
    oSheet = (Excel._Worksheet)oWB.Sheets[1];

    //This works good: (but need something similar)
    oSheet.Cells[7, 2] = "The cell content";

    //Need to access to cell like this:
    oSheet.Cells["B7"] = "The cell content";


    oWB.Close();
}
catch (Exception theException)
{
    String errorMessage;
    errorMessage = "Error: ";
    errorMessage = String.Concat(errorMessage, theException.Message);
    errorMessage = String.Concat(errorMessage, " Line: ");
    errorMessage = String.Concat(errorMessage, theException.Source);

    MessageBox.Show(errorMessage, "Error");
}
1

There are 1 best solutions below

4
user2250152 On BEST ANSWER

When using Range interface, you can access cell(s) by an address

// one cell
var range = oSheet.Range["B8"];
range.Value = "The cell content";

// more cells like B8, B9, C8, C9
var range = oSheet.Range["B8", "C9"];
range.Value = "The cell content";