SAP ABAP如何將內表的資料匯出到EXCEL
阿新 • • 發佈:2019-01-11
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.
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
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
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.