5

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.

Neil Knight
  • 47,437
  • 25
  • 129
  • 188
AJ_
  • 135
  • 2
  • 3
  • 6

6 Answers6

11

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:

Community
  • 1
  • 1
Slai
  • 22,144
  • 5
  • 45
  • 53
  • 1
    Posts like this make me miss the SO Documentation. This would have been a perfect entry. Thanks! – webworm Jan 08 '18 at 14:11
8

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

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

Neil Knight
  • 47,437
  • 25
  • 129
  • 188
  • 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. – BrewMate Feb 02 '17 at 16:59
2

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

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

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.

Mike
  • 661
  • 5
  • 10
1

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.

Billy
  • 11
  • 1
0
I can suggest one more way is (If you need to read string from row 3 column "I":
    Excel.Application objExcel = new Excel.Application();
    objExcel.Visible = true;
    Excel.Workbook objBook = o     objExcel.Workbooks.Open("C:\\myexcel.xlsx");
    Excel.Worksheet objsheet =  objBook.Worksheets["Sheet1"];
    string a = Convert.ToString(objsheet.Cells.get_Item(3,"I").Value);