xsharp.eu • reading excel cell
Page 1 of 1

reading excel cell

Posted: Mon Nov 29, 2021 12:50 pm
by vzeljko
I have problem reading excel cell. Here is my code:

LOCAL cExelFile AS STRING
LOCAL oExcel AS Microsoft.Office.Interop.Excel.Application
LOCAL oWorkbook AS Workbook
LOCAL oWorksheet AS Worksheet


oExcel := Microsoft.Office.Interop.Excel.Application{}
oExcel:Visible := FALSE
oWorkbook := oExcel:Workbooks:Open(Path.Combine( cDataPath, cExelFile ))
oWorksheet := oWorkbook:ActiveSheet // error XS0266

TRY
SELF:oPrTextBox:Text := oWorksheet:Cells[3, 5]:Value:ToString() // error XS1061

CATCH oEx AS Exception
MessageBox:Show(oEx:ToString())
FINALLY
oWorkbook:Close()
END TRY



error XS0266: Cannot implicitly convert type 'object' to 'Microsoft.Office.Interop.Excel.Worksheet'. An explicit conversion exists (are you missing a cast?)
error XS1061: 'object' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
Compilation failed (2 errors)

Does anybody have any idea?

Zeljko

reading excel cell

Posted: Mon Nov 29, 2021 12:58 pm
by wriedmann
Hi Zeljko,
in .NET you have to cast:

Code: Select all

oWorksheet := (  WorkSheet (oWorkbook:ActiveSheet
if the instance variable WorkBook:WorkSheet is defined as generic object.
Wolfgang

reading excel cell

Posted: Mon Nov 29, 2021 1:14 pm
by vzeljko
Thanks Wolfgang. Your suggestion solved first problem, but after compiling I got another one:

error XS1061: 'object' does not contain a definition for 'Cells' and no accessible extension method 'Cells' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

for this line:
SELF:oPrTextBox:Text := oWorksheet:Cells[3, 5]:Value:ToString()

Zeljko

reading excel cell

Posted: Mon Nov 29, 2021 1:28 pm
by ic2
Hello Zeljko,

See this discussion: https://www.xsharp.eu/forum/private-pro ... stion#8173

My X# Excel code now looks as follows:

oWorkbooks:Open(cExcelFile)
oWorkSheet:=(Worksheet)oExcel:Worksheets[1] // Changed 5-8-2020 from //oWorkSheet:=oExcel:ActiveSheet this gives error Cannot implicitly convert type 'object' to 'Microsoft.Office.Interop.Excel.Worksheet'. An explicit conversion exists (are you missing a cast?) // To activate the first sheet
oRange:=oWorkSheet:UsedRange


and further:

For nRow:= 1 Upto nRowCount
dr:=dt:NewRow()
For nCol:=1 Upto nColCount
oCell := (Range) oRange:Cells[nRow, nCol]
cContent := AsString(oCell:Value2)

(etc)
This should work

Dick

reading excel cell

Posted: Mon Nov 29, 2021 3:07 pm
by vzeljko
Thanks Dick. Works fine.

Zeljko