How can I extract a string from an excel cell?

34,867

Solution 1

string myString = xlws.Cells[1, 1].Value as string;

string myString = ((Excel.Range)workSheet.Cells[1, 1]).Value2.ToString();

Solution 2

To avoid NullReferenceException, don't use .ToString() directly on types that can be null (object, dynamic, string, etc.). Here are few safer ways to convert object to string:

Solution 3

There are a couple of ways to get the values from an excel docuemnt but the way I think you're looking for is:

Range range = xlws.get_range("A1", "A1");
object[] data = range.get_Value(XlRangeValueDataType.xlRangeValueDefault);
string str = (string)data[0];

A nice article that explains the other ways too is available here

Hope that helps.

Solution 4

xlws.Cells[1, 1].Value has type object. So you should indicate the type For examples:

xlws.Cells[1,1].Value.ToString();

Solution 5

string val = sheet.Cells[1, 6].Text;

This was the best method to get text from cell. I could get just same text without any change.

Share:
34,867
AJ_
Author by

AJ_

Updated on March 11, 2020

Comments

  • AJ_
    AJ_ about 4 years

    I know how to write to a cell, but how do I get an already existing string written inside a cell in an excel file into a string object so I can use it to generate data in other cells?

    My code so far:

            Excel.ApplicationClass excelApp = new Excel.ApplicationClass();
    
            excelApp.Visible = true;
    
            Excel.Workbook excelWorkbook = excelApp.Workbooks.Open("C:\\Users\\user\\Desktop\\list.xls", 0, false, 5, "", "",
            false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
    
            Excel.Sheets excelSheets = excelWorkbook.Worksheets;
    
            string currentSheet = "Sheet1";
            Excel.Worksheet xlws = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
    

    I can manipulate cell contents using something like:

    xlws.Cells[1,1] = "foo";

    But I'm having trouble doing the opposite, that is reading cell contents into a string in my program.

    Any help would be appreciated.

  • BrewMate
    BrewMate about 7 years
    I gave Slai an upvote because he is right when dealing with strings, you should use Convert.ToString(object) instead of ToString(). Switching this in my project just now fixed my null reference.
  • webworm
    webworm over 6 years
    Posts like this make me miss the SO Documentation. This would have been a perfect entry. Thanks!