Foro de programación ABAP
SAP / ABAP => Programación ABAP => Mensaje iniciado por: carlogio en 29 de Noviembre de 2007, 11:24:24 am
-
Buenas. Tengo que leer un archivo de excel, para lo que estoy usando ALSM_EXCEL_TO_INTERNAL_TABLE, que por ahora me va bien, pero el archivo excel tiene varias hojas, con lo que SAP abre la que esté activa, y si no es la correcta, da error. Se puede seleccionar una hoja u otra de alguna forma??
gracias
-
Hola, este es un ejemplo de como trabajar con las hojas de un excel.
Este programa lo encontré en internet y me llamó la atención, pero nunca lo he tenido que usar.
Espero que te sea de ayuda.
REPORT ztestme.
TYPE-POOLS ole2.
TABLES: bsid. "Contabilidad: índice secundario para deudores
SELECT-OPTIONS: s_kunnr FOR bsid-kunnr.
DATA: excel TYPE ole2_object,
application TYPE ole2_object,
books TYPE ole2_object,
book TYPE ole2_object,
sheet TYPE ole2_object,
cell TYPE ole2_object,
column TYPE ole2_object.
DATA: v_kunnr LIKE bsid-kunnr, "Nº de cliente
v_no TYPE i,
v_ln TYPE i,
v_tabix LIKE sy-tabix,
v_index LIKE sy-index,
v_sheet(10),
row TYPE i.
DATA: BEGIN OF itab OCCURS 10,
index LIKE sy-index,
kunnr LIKE bsid-kunnr, "Nº de cliente
END OF itab.
DATA: BEGIN OF jtab OCCURS 50,
kunnr LIKE bsid-kunnr, "Nº de cliente
gjahr LIKE bsid-gjahr, "Ejercicio
budat LIKE bsid-budat, "Fecha de contabilización en el documento
wrbtr LIKE bsid-wrbtr, "Importe en la moneda del documento
END OF jtab.
SELECT kunnr gjahr budat wrbtr
INTO (jtab-kunnr, jtab-gjahr, jtab-budat, jtab-wrbtr)
FROM bsid
WHERE bukrs = '0010'
AND kunnr IN s_kunnr
ORDER BY kunnr.
IF sy-subrc EQ 0.
itab-kunnr = jtab-kunnr.
APPEND itab.
CLEAR itab.
APPEND jtab.
CLEAR jtab.
ENDIF.
ENDSELECT.
DELETE ADJACENT DUPLICATES FROM itab.
LOOP AT itab.
v_index = v_index + 1.
itab-index = v_index.
MODIFY itab TRANSPORTING index.
ENDLOOP.
DELETE itab WHERE index > 3.
IF NOT itab[] IS INITIAL.
CREATE OBJECT excel 'EXCEL.SHEET'.
GET PROPERTY OF excel 'Application' = application.
SET PROPERTY OF application 'Visible' = 1.
CALL METHOD OF application 'Workbooks' = books.
CALL METHOD OF books 'Add' = book.
LOOP AT itab.
v_sheet = itab-kunnr.
v_no = v_no + 1. row = 1.
PERFORM fill_sheet USING v_no v_sheet.
ENDLOOP.
FREE OBJECT: column, sheet, book, books, application,
excel NO FLUSH.
CALL FUNCTION 'FLUSH'.
ENDIF.
*&---------------------------------------------------------------------*
*& Form FILL_SHEET
*&---------------------------------------------------------------------*
FORM fill_sheet USING v_no v_sheet.
CALL METHOD OF book 'worksheets' = sheet NO FLUSH EXPORTING #1 = v_no.
SET PROPERTY OF sheet 'Name' = v_sheet no flush.
LOOP AT jtab WHERE kunnr = v_sheet.
PERFORM fill_cell USING row 1 jtab-kunnr.
PERFORM fill_cell USING row 2 jtab-gjahr.
PERFORM fill_cell USING row 3 jtab-budat.
PERFORM fill_cell USING row 4 jtab-wrbtr.
row = row + 1.
ENDLOOP.
CALL METHOD OF sheet 'Columns' = column NO FLUSH.
FREE OBJECT sheet NO FLUSH.
CALL METHOD OF column 'Autofit' NO FLUSH.
FREE OBJECT column NO FLUSH.
CALL FUNCTION 'FLUSH'.
ENDFORM. " FILL_SHEET
*&---------------------------------------------------------------------*
*& Form FILL_CELL
*&---------------------------------------------------------------------*
FORM fill_cell USING row col val.
CALL METHOD OF sheet 'cells' = cell NO FLUSH
EXPORTING #1 = row #2 = col.
SET PROPERTY OF cell 'value' = val.
FREE OBJECT cell NO FLUSH.
ENDFORM. " FILL_CELL
-
corrigeme si me equivoco, pero eso lo que hace no es crear un excel????? yo el excel ya lo tengo. Lo que quiero es leer una de las hojas (o pestañas).
Si guardan el excel con la pestaña incorrecta abierta, la funcion que os he puesto, lee la pestaña incorrecta, con lo q salen errores por todos lados
-
sigo batallando, y he conseguido descubir que con ALSM_EXCEL_TO_INTERNAL_TABLE no se diferencian hojas, que solo trabaja con la activa... así que estoy intentando activarla. He conseguido hacer esto:
TYPE-POOLS ole2.
DATA: application TYPE ole2_object,
workbook TYPE ole2_object,
worksheet TYPE ole2_object.
CREATE OBJECT application 'Excel.Application'.
CALL METHOD OF application 'Workbooks' = workbook.
CALL METHOD OF workbook 'Open' EXPORTING #1 = fichero.
SET PROPERTY OF application 'ACTIVESHEET' = 'Hoja1'.
CALL METHOD OF workbook 'Quit'.
"fichero" es la variable donde guardo la ruta al excel, y hoja 1 es el nombre de la primera hoja... Pero nada... ayuda please :s
-
Efectivamente, con esa función solo puedes recoger la hoja que está activa una vez cerrado el excel.
Me pasó lo mismo una vez, al final me pasaron las hojas del excel divididas en tantos excel como hojas contenía. Lo que hice fue ir abriendo excel por excel.
Sería muy interesante saber si hay alguna manera de hacerlo!!! :P
-
sigo a la espera. Nadie puede ayudarme?
-
Buenos días,
Os incluyo una función para leer datos de un Excel con varias hojas
function zbc_open_excel .
*"----------------------------------------------------------------------
*"*"Interfase local
*" IMPORTING
*" REFERENCE(FILENAME) TYPE RLGRAP-FILENAME
*" REFERENCE(I_BEGIN_COL) TYPE I
*" REFERENCE(I_BEGIN_ROW) TYPE I
*" REFERENCE(I_END_COL) TYPE I
*" REFERENCE(I_END_ROW) TYPE I
*" TABLES
*" T_EXCEL TYPE ZTB_BC_EXCEL
*" EXCEPTIONS
*" INCONSISTENT_PARAMETERS
*" UPLOAD_OLE
*"----------------------------------------------------------------------
* Variables Locales
data: l_excel type ole2_object,
l_libro type ole2_object,
l_hoja type ole2_object,
l_cont type i,
l_celli type ole2_object,
l_cellf type ole2_object,
l_cell type ole2_object,
lt_tabla type table of zes_bc_excel_ln.
field-symbols: <lf_aux>.
* Abrimos el Excel
if l_excel-header = space or l_excel-handle = -1.
create object l_excel 'Excel.Application'.
endif.
call method of l_excel 'Workbooks' = l_libro.
call method of l_libro 'Open'
exporting
#1 = filename.
check sy-subrc is initial.
* Recorremos las Hojas del Excel
do.
*-- Incrementamos el Contador
add 1 to l_cont.
*-- Limpiamos los objetos
free object: l_cell, l_celli, l_cellf, l_hoja.
clear lt_tabla[].
*-- Leemos la Hoja
call method of l_excel 'Worksheets' = l_hoja
exporting #1 = l_cont.
*-- Si no existe la hoja Salimos del Bucle
if not sy-subrc is initial. "OR l_cont EQ 3.
exit.
endif.
*-- Recogemos la Primera Celda
call method of l_hoja 'Cells' = l_celli
exporting
#1 = i_begin_row
#2 = i_begin_col.
commit work and wait.
*-- Recogemos la Ultima Celda
call method of l_hoja 'Cells' = l_cellf
exporting
#1 = i_end_row
#2 = i_end_col.
commit work and wait.
*-- Recogemos las celdas comprendidas entre la Primera y la Ultima
*-- y lo copiamos a la memoria intermedia
call method of l_hoja 'RANGE' = l_cell
exporting
#1 = l_celli
#2 = l_cellf.
commit work and wait.
call method of l_cell 'SELECT'.
commit work and wait.
call method of l_cell 'COPY'.
*-- Recogemos los Valores
call method cl_gui_frontend_services=>clipboard_import
importing
data = lt_tabla
exceptions
cntl_error = 1
error_no_gui = 2
not_supported_by_gui = 3
others = 4.
*-- Limpiamos los valores en blanco
sort lt_tabla.
delete lt_tabla where line eq space.
clear: sy-subrc.
*-- Recogemos los datos a la tabla de Salida
check not lt_tabla[] is initial.
assign lt_tabla[] to <lf_aux>.
check sy-subrc is initial.
move <lf_aux> to t_excel-tabla.
append t_excel. clear t_excel.
enddo.
* Cerramos el Excel
call method of l_excel 'QUIT'.
*-- Limpiamos los objetos
free object l_libro.
free object l_hoja.
endfunction.
La tabla ZTB_BC_EXCEL es de "Tipo Tabla" con tipo de linea una estructura con un campo de formato char4092.
Está montada asi para crear una tabla con todo el contenido del excel, con múltiples "subtablas", tantas como hojas contenga el excel.
Es una función beta, pero funciona.
Uvidime sa,
ADGP
-
Muchas gracias por la funcion...
Muy buena.
;)
-
Anexo una imagen con las tablas Z a las que se hace referencia (si es que me sale).
(http://img120.imageshack.us/img120/7607/dibujotu8.th.jpg) (http://img120.imageshack.us/my.php?image=dibujotu8.jpg)
Repito que es BETA, a si que está expuesta a mejoras. Si veis algo raro no dudéis en comentarlo.
Estoy trabajando para hacer la inversa y generar un excel con múltiples hojas a partir de una tabla. Tengo un problema para dar formato a los campos numéricos y para ejecutarse en fondo, cuando consiga solucionarlo la publico.
Uvidime sa,
ADGP
-
Gracias a la introducción que nos ha dado nuestro amigo ADGP. Mi compañero ha realizado una función que de forma muy sencilla podemos leer un libro excel.
Este es el enlace donde lo podéis encontrar.
http://www.abap.es/foro/index.php?topic=217.msg443#msg443
;)