abap 动态导出excel表
时间: 2023-11-19 19:40:21 浏览: 170
您可以使用以下代码动态导出 Excel 表格:
```
TYPES:
BEGIN OF ty_tab,
col1 TYPE string,
col2 TYPE string,
END OF ty_tab.
DATA:
lt_data TYPE STANDARD TABLE OF ty_tab,
lr_excel TYPE ole2_object,
lr_workbook TYPE ole2_object,
lr_worksheet TYPE ole2_object,
lr_range TYPE ole2_object,
lr_cell TYPE ole2_object.
FIELD-SYMBOLS:
<fs_data> LIKE LINE OF lt_data.
* 填充数据
APPEND VALUE #( col1 = 'A' col2 = 'B' ) TO lt_data.
APPEND VALUE #( col1 = 'C' col2 = 'D' ) TO lt_data.
* 创建 Excel 对象
CREATE OBJECT lr_excel 'Excel.Application'.
IF sy-subrc <> 0.
MESSAGE 'Failed to create Excel object' TYPE 'E'.
EXIT.
ENDIF.
* 创建工作簿
CALL METHOD OF lr_excel 'Workbooks' = lr_workbook.
IF sy-subrc <> 0.
MESSAGE 'Failed to create workbook' TYPE 'E'.
EXIT.
ENDIF.
* 创建工作表
CALL METHOD OF lr_workbook 'Worksheets' = lr_worksheet 1.
IF sy-subrc <> 0.
MESSAGE 'Failed to create worksheet' TYPE 'E'.
EXIT.
ENDIF.
* 写入数据
LOOP AT lt_data ASSIGNING <fs_data>.
CALL METHOD OF lr_worksheet 'Cells' = lr_cell
EXPORTING
#1 = sy-tabix
#2 = 1.
IF sy-subrc <> 0.
MESSAGE 'Failed to get cell' TYPE 'E'.
EXIT.
ENDIF.
CALL METHOD OF lr_cell 'Value' = <fs_data>-col1.
CALL METHOD OF lr_worksheet 'Cells' = lr_cell
EXPORTING
#1 = sy-tabix
#2 = 2.
IF sy-subrc <> 0.
MESSAGE 'Failed to get cell' TYPE 'E'.
EXIT.
ENDIF.
CALL METHOD OF lr_cell 'Value' = <fs_data>-col2.
ENDLOOP.
* 设置单元格格式
CALL METHOD OF lr_worksheet 'Range' = lr_range 'A1:B1'.
IF sy-subrc <> 0.
MESSAGE 'Failed to get range' TYPE 'E'.
EXIT.
ENDIF.
CALL METHOD OF lr_range 'Font' = lr_cell 'Bold' = '1'.
CALL METHOD OF lr_range 'HorizontalAlignment' = 1.
* 保存文件
CALL METHOD OF lr_workbook 'SaveAs'
EXPORTING
#1 = 'C:\temp\excel_file.xlsx'
#2 = 51.
* 关闭文件
CALL METHOD OF lr_workbook 'Close'.
CALL METHOD OF lr_excel 'Quit'.
```
在此示例中,我们创建了一个类型为 `ty_tab` 的内部表 `lt_data`,其中包含两个字符串字段 `col1` 和 `col2`。我们将两行数据添加到内部表中,并使用 OLE2 创建一个 Excel 对象。然后,我们创建一个工作簿和一个工作表,并将数据写入工作表中。最后,我们设置单元格格式、保存文件并关闭工作簿和 Excel 对象。
阅读全文