How can I extract a string from an excel cell?

…衆ロ難τιáo~ 提交于 2019-11-28 11:35:14

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

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

Slai

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:

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

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

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.

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.

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);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!