作者: SAP道长
将内表的数据导出到EXCEL
REPORT ZTEST08.
DATA: BEGIN OF MY_DATA,
MANDT LIKE USR02-MANDT,
BNAME LIKE USR02-BNAME,
ERDAT LIKE USR02-ERDAT,
LTIME LIKE USR02-LTIME,
END OF MY_DATA.
DATA: IT_DATA LIKE MY_DATA OCCURS 0.
SELECT USR02~MANDT USR02~BNAME USR02~ERDAT USR02~LTIME
APPENDING TABLE IT_DATA
FROM USR02
UP to 100 rows.
*排序
SORT IT_DATA BY BNAME.
INCLUDE OLE2INCL. "定义OLE变量
DATA: EXCEL TYPE OLE2_OBJECT,
SHEET TYPE OLE2_OBJECT,
CELL TYPE OLE2_OBJECT,
WORKBOOK TYPE OLE2_OBJECT,
XLSNAME TYPE STRING VALUE 'C:\sap_usr02.xls',
LINE TYPE I VALUE 0. "行号
CREATE OBJECT EXCEL 'EXCEL.APPLICATION'."启动Excel
IF SY-SUBRC NE 0.
WRITE: / '启动Excel失败。'.
STOP.
ENDIF.
CALL METHOD OF EXCEL 'WORKBOOKS' = WORKBOOK.
SET PROPERTY OF EXCEL 'VISIBLE' = 1. "使excel 可视
SET PROPERTY OF EXCEL 'SHEETSINNEWWORKBOOK' = 1. "如果是读取excel文件中的内容 则是直接打开工作簿第一页
CALL METHOD OF WORKBOOK 'ADD'. "例如:CALL METHOD OF EXCEL 'WORKSHEETS' = SHEET EXPORTING #1 = 1.
LOOP AT IT_DATA INTO MY_DATA.
LINE = LINE + 1. "Excel 中行号从1开始
CALL METHOD OF EXCEL 'CELLS' = CELL EXPORTING #1 = LINE #2 = 1. "指定单元格,
SET PROPERTY OF CELL 'VALUE' = MY_DATA-MANDT. "写入值
CALL METHOD OF EXCEL 'CELLS' = CELL EXPORTING #1 = LINE #2 = 2. "指定单元格,
SET PROPERTY OF CELL 'VALUE' = MY_DATA-BNAME. "写入值
CALL METHOD OF EXCEL 'CELLS' = CELL EXPORTING #1 = LINE #2 = 3. "指定单元格,
SET PROPERTY OF CELL 'VALUE' = MY_DATA-ERDAT. "写入值
CALL METHOD OF EXCEL 'CELLS' = CELL EXPORTING #1 = LINE #2 = 4. "指定单元格,
SET PROPERTY OF CELL 'VALUE' = MY_DATA-LTIME. "写入值
ENDLOOP.
GET PROPERTY OF EXCEL 'ACTIVESHEET' = SHEET. "激活工作簿
GET PROPERTY OF EXCEL 'ACTIVEWORKBOOK' = WORKBOOK. "激活工作区
CALL METHOD OF WORKBOOK 'SAVEAS' EXPORTING #1 = XLSNAME #2 = 1. "将excel文件保存
CALL METHOD OF WORKBOOK 'CLOSE'. "关闭工作区
CALL METHOD OF EXCEL 'QUIT'. "退出excel
*WRITE:/ XLSNAME,'DONE'. "退出成功,输出done
FREE OBJECT SHEET. "释放操作
FREE OBJECT WORKBOOK.
FREE OBJECT EXCEL.