如何从excel单元格中提取字符串?

AJ_*_*AJ_ 4 c# string excel cell

我知道如何写入单元格,但是如何将excel文件中单元格内已写入的字符串写入字符串对象中,以便我可以使用它在其他单元格中生成数据?

我的代码到目前为止:

        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);
Run Code Online (Sandbox Code Playgroud)

我可以使用以下方法操作单元格内容:

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

但是我正在做相反的事情,那就是在我的程序中将单元格内容读入一个字符串.

任何帮助,将不胜感激.

Nei*_*ght 8

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

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


Sla*_*lai 6

要避免NullReferenceException,不要使用.ToString()上直接类型可以为空(object,dynamic,string等).以下是将对象转换为字符串的几种更安全的方法: