Friday, December 3, 2010

Convert ABAP Spool to word document

*&---------------------------------------------------------------------*
*& Report Z_SPOOL_2_WORD
*&
*&---------------------------------------------------------------------*
*&
*&
*&---------------------------------------------------------------------*

REPORT Z_SPOOL_2_WORD.

INCLUDE ole2incl.

DATA i_buffer(132) OCCURS 0 WITH HEADER LINE.

SELECTION-SCREEN BEGIN OF BLOCK B1 WITH FRAME TITLE text-001.

PARAMETERS: p_spool LIKE tsp01-rqident OBLIGATORY.

SELECTION-SCREEN END OF BLOCK B1.

SELECTION-SCREEN BEGIN OF BLOCK B2 WITH FRAME TITLE text-002.

PARAMETERS: p_word AS CHECKBOX DEFAULT 'X'.
PARAMETERS: p_fwor LIKE rlgrap-filename obligatory.

SELECTION-SCREEN END OF BLOCK B2.

*----------------------------------------------------------------------*
* START-OF-SELECTION.
*----------------------------------------------------------------------*
START-OF-SELECTION.
PERFORM read_spool.

IF NOT p_word IS INITIAL.
PERFORM write_word.
ENDIF.

*&---------------------------------------------------------------------*
*& Form read_spool
*&---------------------------------------------------------------------*
* Read spool data
*----------------------------------------------------------------------*
FORM read_spool.

CALL FUNCTION 'RSPO_RETURN_ABAP_SPOOLJOB'
EXPORTING
rqident = p_spool
first_line = 1
last_line = 9999999
TABLES
buffer = i_buffer
EXCEPTIONS
no_such_job = 1
not_abap_list = 2
job_contains_no_data = 3
selection_empty = 4
no_permission = 5
can_not_access = 6
read_error = 7
OTHERS = 8.

IF sy-subrc NE 0.
MESSAGE e398(00) WITH 'Spool' p_spool 'not found'.
ENDIF.

ENDFORM. " read_spool

*&---------------------------------------------------------------------*
*& Form write_word
*&---------------------------------------------------------------------*
* Write to word.
*----------------------------------------------------------------------*
FORM write_word.

DATA: wordapp TYPE ole2_object,
document TYPE ole2_object,
selection TYPE ole2_object.

CALL FUNCTION 'CLPB_EXPORT'
TABLES
data_tab = i_buffer
EXCEPTIONS
clpb_error = 1
OTHERS = 2.

* Word CREATE
CREATE OBJECT wordapp 'word.application'.

IF sy-subrc NE 0.
MESSAGE e398(00) WITH 'Word cannot be created'.
ENDIF.

* Set visible
SET PROPERTY OF wordapp 'Visible' = 1.

CALL METHOD OF wordapp 'Documents' = document.

CALL METHOD OF document 'Add'.

CALL METHOD OF wordapp 'Selection' = selection.

CALL METHOD OF selection 'Paste'.

IF sy-subrc NE 0.
MESSAGE e398(00) WITH 'Error at writing to the document'.
ENDIF.

CALL METHOD OF wordapp 'ActiveDocument' = document.

CALL METHOD OF document 'SaveAs'
EXPORTING #1 = p_fwor.

IF sy-subrc NE 0.
MESSAGE e398(00) WITH 'Error saving the document'.
ENDIF.

* Close Word application

CALL METHOD OF WORDAPP 'Quit'.

IF sy-subrc NE 0.
MESSAGE e398(00) WITH 'Error closing Word'.
ENDIF.

ENDFORM. "write_word

No comments:

Post a Comment