转自:https://www.cnblogs.com/jxzhu/p/8708686.html
OLE整理:
1.定义,分别对应EXCEL,workbook(工作簿),sheet(页),单元格
DATA: EXCEL_OBJ TYPE OLE2_OBJECT, BOOK_OBJ TYPE OLE2_OBJECT, SHEET_OBJ TYPE OLE2_OBJECT, CELL_OBJ TYPE OLE2_OBJECT.
2.方法说明:
CREATE OBJECT name_obj 'app'."创建APP应用类的一个对象obj_name实例 SET PROPERTY OF name_obj 'XXX' = f ."设置对象NAME_obj属性xxx为值f GET PROPERTY OF name_obj 'xxx' = f ."将name_obj的属性xxx的值获取赋给f CALL METHOD OF name_obj 'xxx' = f "由f来接收返回值 EXPORTING #1 = f1. "调用name_obj的方法xxx 传入参数f1…fn FREE OBJECT name_obj . "释放.
3.创建对象
CREATE OBJECT EXCEL_OBJ 'EXCEL.APPLICATION'. SET PROPERTY OF EXCEL_OBJ 'VISIBLE' = 1."使excel可见(1:可见 0:后台运行不可见) SET PROPERTY OF EXCEL_OBJ 'SHEETSINNEWWORKBOOK' = 1."设置 Microsoft Excel 软件打开时,自动插入到新工作簿中的工作表数目(即初始sheet数目,默认名字依次为 Sheet1、Sheet2.....)
CALL METHOD OF EXCEL_OBJ 'WORKBOOKS' = BOOK_OBJ. "由于Workbooks同时为属性,所以可以使用下面语句代替上面语句 *GET PROPERTY OF EXCEL 'Workbooks' = WORKBOOK_OBJ . CALL METHOD OF BOOK_OBJ 'ADD'. CALL METHOD OF BOOK_OBJ 'OPEN'EXPORTING #1 = 'c:\***.xlsx'."开文件
5.增添sheet
CALL METHOD OF EXCEL_OBJ 'sheets' = SHEET_OBJ. CALL METHOD OF SHEET_OBJ 'Add'. SET PROPERTY OF SHEET_OBJ 'Name' = 'NAME'."sheet重命名
6.切换sheet
CALL METHOD OF EXCEL_OBJ 'Worksheets' = SHEET EXPORTING #1 = 'sheet3'. CALL METHOD OF SHEET_OBJ 'Activate'.
7.给单元格赋值
CaLL METHOD OF EXCEL_OBJ 'CELLS' = CELL EXPORTING #1 = row #2 = col. SET PROPERTY OF CELL_OBJ 'value' = xxxx.
8.执行宏
CALL METHOD OF EXCEL_OBJ 'RUN' EXPORTING #1 = 'ZRUNM'.
9.保存和退出
PS:如果遇到程序执行完之后 EXCEL后台未关闭的时候,检查一下 有没有在保存操作前 执行激活
GET PROPERTY OF EXCEL_OBJ 'ACTIVESHEET' = SHEET."激活工作簿 GET PROPERTY OF EXCEL_OBJ 'ACTIVEWORKBOOK' = WORKBOOK."激活工作区 CALL METHOD OF BOOK_OBJ 'SAVEAS'EXPORTING #1 = 'c:\1.xls' #2 = 1. "另存为 "CALL METHOD OF BOOK_OBJ 'SAVE'."保存 CALL METHOD OF BOOK_OBJ 'CLOSE'. "关闭工作区 CALL METHOD OF EXCEL_OBJ 'QUIT'."退出excel
10.释放资源
FREE OBJECT SHEET_OBJ. FREE OBJECT WORKBOOK_OBJ. FREE OBJECT EXCEL_OBJ.