开发者

How can I extract a string from an excel cell?

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;

       开发者_如何学JAVA 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.


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:

  • Convert.ToString(object) - returns String.Empty when object is null

  • object?.ToString() - VS 2015 Null-conditional Operator returns null if object is null

  • object?.ToString() ?? "" - C# null-coalescing operator ?? to return "" when object is null

  • object + "" - String.Concat to return "" when object is null

  • $"{object}" - VS 2015 string interpolation is transformed at compile time to invoke an equivalent String.Format("{0}", object) call, and returns "" when object is null


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

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


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜