Tarasov
Tarasov

Reputation: 3695

How I can read a cell in excel with C#?

I want to make an excel tool in C#. The tool must open every excel document in a folder and look in the cell E1 for a value. If the cell holds the value I searched for it will be deleted and the document will save. Then the application will move on to the next excel file.

I can open the document but I can't look in the cell for the value.

Here my code:

using Microsoft.Office.Interop.Excel;

//Preparing the required items
Microsoft.Office.Interop.Excel.Application excel = null;
Workbook wb = null;

//Start Excel 
excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = false;

try
{
    //Open file
    wb = excel.Workbooks.Open(
        @"C:\Users\....",
        ExcelKonstanten.UpdateLinks.DontUpdate,
        ExcelKonstanten.ReadOnly,
        ExcelKonstanten.Format.Nothing,
        "", //Password
        "", //WriteResPasswort
        ExcelKonstanten.IgnoreReadOnlyRecommended,
        XlPlatform.xlWindows,
        "", //Separator
        ExcelKonstanten.Editable,
        ExcelKonstanten.DontNotifiy,
        ExcelKonstanten.Converter.Default,
        ExcelKonstanten.DontAddToMru,
        ExcelKonstanten.Local,
        ExcelKonstanten.CorruptLoad.NormalLoad);

    //Read sheets
    Sheets sheets = wb.Worksheets;

    //Select a sheet…
    Worksheet ws = (Worksheet)sheets.get_Item("Tabelle1");
    //…or a cell
    Range range = (Range)ws.get_Range("E", "1");
    //Read out the value
    string zellwert = range.Value2.ToString(); // <--- This is where I get the error!
    string zellwert = range.Value2; 
    Console.WriteLine(zellwert);
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}
finally
{
    wb.Close(false, null, null);
    excel.Quit();
}

Console.WriteLine("Prüfung abgeschlossen...");

I try the same thing in this page:

http://blog.stefan-macke.com/2006/06/28/c-projekt-zugriff-auf-excel-dateien/

Upvotes: 0

Views: 6794

Answers (1)

spirosvp
spirosvp

Reputation: 130

I thing you should look your code again. When you ask for a range you put the from which to which shell you want to read.

For example:

Range range = ( Range ) ws. get_Range ( "E1" , "E1" ) ;

Upvotes: 2

Related Questions