How can I extract a row from an excel cell?

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

My code is:

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 the contents of the cell using something like:

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

But I am having problems with the opposite: reading the contents of a cell into a string in my program.

Any help would be appreciated.

+4
source share
6 answers

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

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

+6
source

To avoid a NullReferenceException , do not use .ToString() directly for types that may be empty ( object , dynamic , string , etc.). The following are some safer ways to convert an object to a string:

+5
source

xlws.Cells [1, 1] .Value is of type object . Therefore, you must specify the type of Examples:

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

There are several ways to get values ​​from an excel document, but as I think you are looking for:

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

A good article that explains other ways is also available here.

Hope this helps.

+2
source

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

This was the best way to get text from a cell. I could get the same text without any changes.

+1
source
 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
source

Source: https://habr.com/ru/post/1347868/


All Articles