代码:
INCLUDE OLE2INCL.
DATA: GS_EXCEL TYPE OLE2_OBJECT ,
GS_WBOOKLIST TYPE OLE2_OBJECT,
GS_SHEETS TYPE OLE2_OBJECT,
GS_CELL1 TYPE OLE2_OBJECT ,
CELL TYPE OLE2_OBJECT,
ROWS TYPE OLE2_OBJECT,
ROWS_I TYPE I,
LC_FULLPATH TYPE STRING,
INCITEM TYPE I,INC TYPE I,P_VALUE(20) TYPE C,P_NAME TYPE STRING,STRVISIBLE TYPE C.
LC_FULLPATH = 'C:\XXXX\123.xlsx'.
CREATE OBJECT GS_EXCEL 'EXCEL.APPLICATION'."创建应用程序对象
IF SY-SUBRC <> 0.
MESSAGE '打开文件失败!' TYPE 'S'.
EXIT.
ENDIF.
"打开一个工作簿
GET PROPERTY OF GS_EXCEL 'Workbooks' = GS_WBOOKLIST .
CALL METHOD OF GS_WBOOKLIST 'OPEN'
EXPORTING
#1 = LC_FULLPATH.
GET PROPERTY OF GS_EXCEL 'Sheets' = GS_SHEETS."选择特定的工作表
GET PROPERTY OF GS_SHEETS 'Count' = INCITEM."得到工作表个数
DO INCITEM TIMES."循环工作表
INC = INC + 1.
GET PROPERTY OF GS_EXCEL 'Sheets' = GS_SHEETS"选择特定的工作表
EXPORTING
#1 = INC.
CALL METHOD OF GS_SHEETS 'Select'.
CALL METHOD OF GS_SHEETS 'ACTIVATE'.
CALL METHOD OF GS_SHEETS 'Name' = P_NAME."获得工作表名称
IF SY-INDEX = 1."是否显示应用程序
IF STRVISIBLE = 'X'.
SET PROPERTY OF GS_EXCEL 'Visible' = 1."显示
ELSE.
SET PROPERTY OF GS_EXCEL 'Visible' = 0."隐藏
ENDIF.
ENDIF.
"获取行数
CALL METHOD OF GS_SHEETS 'UsedRange' = CELL.
CALL METHOD OF CELL 'Rows' = ROWS.
CALL METHOD OF ROWS 'Count' = ROWS_I.
DO ROWS_I TIMES ."循环获取数据
CALL METHOD OF GS_EXCEL 'Cells' = GS_CELL1"取指定数据
EXPORTING
#1 = SY-INDEX "行
#2 = 1. "列
CALL METHOD OF GS_CELL1 'SELECT'.
GET PROPERTY OF GS_CELL1 'VALUE' = P_VALUE."得到数据,若为数字,可能需要去除小数点
ENDDO.
ENDDO.
CALL METHOD OF GS_EXCEL 'QUIT'."关闭 EXCEL 应用程序释放对象
FREE OBJECT GS_EXCEL.
FREE:GS_EXCEL,GS_SHEETS,CELL,ROWS,GS_CELL1.