SAP R/3 форум ABAP консультантов
Russian ABAP Developer's Club

Home - FAQ - Search - Memberlist - Usergroups - Profile - Log in to check your private messages - Register - Log in - English
Blogs - Weblogs News

создание Excel - ошибка.


Goto page 1, 2  Next
 
Post new topic   Reply to topic    Russian ABAP Developer's Club Forum Index -> ABAP
View previous topic :: View next topic  
Author Message
elsen
Участник
Участник



Joined: 06 Aug 2009
Posts: 17

PostPosted: Thu Aug 06, 2009 7:04 pm    Post subject: создание Excel - ошибка. Reply with quote

помогите найти ошибку, мне знаний пока маловато.
Если цикл работает без создания эксельфайла то все нормально.
После добавления создания эксельфайла не берет следуюшую запись из таблицы а читает всегда токо первую.
Где ошибка?

Code:
form fill_sheet.
  data: wa_lfa1 type lfa1.
  DATA: pr_lifnr type string,
        pr_name  type string,
        pr_ort01 type string.
data: i type integer.
  select * from LFA1 into wa_lfa1.
    do.
      read line sy-index.
      pr_lifnr = wa_lfa1-lifnr.
      pr_name  = wa_lfa1-name1.
      pr_ort01 = wa_lfa1-ort01.

   CALL METHOD  OF EXCEL   'RANGE' = CELL EXPORTING #1 = 'A1'.
   SET PROPERTY OF CELL    'VALUE' = pr_lifnr.
   free object cell.

      if sy-subrc <> 0.
      exit.
      endif.

  enddo.
  endselect.
      WRITE : sy-dbcnt.

endform.
Back to top
View user's profile Send private message
Удав
Гуру
Гуру


Age: 48
Joined: 25 Jan 2008
Posts: 580
Location: Москва

PostPosted: Thu Aug 06, 2009 7:39 pm    Post subject: Reply with quote

1.Вместо select..endselect используйте select ...into table. См. транзакцию ABAPDOCU, раздел "ABAP: Доступы к БД"
2.Судя по коду данные должны всегда писаться в первую ячейку.
3.Для выгрузки данных для начала используйте текстовые файлы: ABAPDOCU, раздел "Язык программирования ABAP - Внешнее хранение данных - работа с файлами - файлы на сервере презентации"

Если обязательно нужен excel, поищите по словам excel ole

_________________
С уважением,
Удав.
Back to top
View user's profile Send private message
vga
Мастер
Мастер


Age: 75
Joined: 04 Oct 2007
Posts: 1218
Location: Санкт-Петербург

PostPosted: Thu Aug 06, 2009 7:57 pm    Post subject: Reply with quote

Сдается, что эти линии вообще тут лишние.

do.
read line sy-index.

if sy-subrc <> 0.
exit.
endif.

enddo.
Back to top
View user's profile Send private message Blog Visit poster's website
tester
Участник
Участник



Joined: 15 Jun 2009
Posts: 3

PostPosted: Fri Aug 07, 2009 9:24 am    Post subject: Reply with quote

Конструкции select..endselect

и
select ...into table.
loop at table.
. . .
endloop.

в большинстве случаев сравнимы по производительности,
поэтому именно в этом случае такая замена особого смысла не имеет.
Back to top
View user's profile Send private message
elsen
Участник
Участник



Joined: 06 Aug 2009
Posts: 17

PostPosted: Fri Aug 07, 2009 11:08 am    Post subject: Reply with quote

Удав wrote:
1.Вместо select..endselect используйте select ...into table. См. транзакцию ABAPDOCU, раздел "ABAP: Доступы к БД"
2.Судя по коду данные должны всегда писаться в первую ячейку.
3.Для выгрузки данных для начала используйте текстовые файлы: ABAPDOCU, раздел "Язык программирования ABAP - Внешнее хранение данных - работа с файлами - файлы на сервере презентации"

Если обязательно нужен excel, поищите по словам excel ole


сама выборка работает без проблем, после добавления кода на сохранения данных в экселе цикл почемуто перестает работать и все время берет токо первую запись. вот ето мне и не понятно
Back to top
View user's profile Send private message
vga
Мастер
Мастер


Age: 75
Joined: 04 Oct 2007
Posts: 1218
Location: Санкт-Петербург

PostPosted: Fri Aug 07, 2009 11:14 am    Post subject: Reply with quote

elsen wrote:
сама выборка работает без проблем, после добавления кода на сохранения данных в экселе цикл почемуто перестает работать и все время берет токо первую запись. вот ето мне и не понятно


Логика вашей программы не совсем понятна из предоставленного куска кода.
Зачем Вы считываете линии с экрана? Где тогда запись на экран?
Code:
read line sy-index

Раз Вы новичек, я предположил в посте выше, что вышеуказанные линии кода вообще не нужны, вы их добавили из-за непонимания операторов языка abap.
Back to top
View user's profile Send private message Blog Visit poster's website
tester
Участник
Участник



Joined: 15 Jun 2009
Posts: 3

PostPosted: Fri Aug 07, 2009 11:25 am    Post subject: Reply with quote

Работает ваш бессмысленный цикл DO ... ENDDO
внутри цикла SELECT ... ENDSELECT.
Back to top
View user's profile Send private message
elsen
Участник
Участник



Joined: 06 Aug 2009
Posts: 17

PostPosted: Fri Aug 07, 2009 12:24 pm    Post subject: Reply with quote

пример я взял отсюда http://sapnet.ru/viewtopic.php?t=1881 только мне нужна выборка из таблицы поетому изменил вконце код, теперь когда я добавляю CALL METHOD OF EXCEL сап находит первую запись а потом ругается и сообшает что надо перед выгрузкой закрыть селект вобшем тупик.
код изменил на
data: wa_lfa1 type lfa1.
DATA: pr_lifnr type string,
pr_name type string,
pr_ort01 type string,
sw_loop type i.

select * from LFA1 into wa_lfa1.


pr_lifnr = wa_lfa1-lifnr.
pr_name = wa_lfa1-name1.
pr_ort01 = wa_lfa1-ort01.
CALL METHOD OF EXCEL 'RANGE' = CELL EXPORTING #1 = 'A1'.
SET PROPERTY OF CELL 'VALUE' = pr_lifnr.

free object cell.
endselect.


p.s

если я опускаю за рамки endselect. CALL METHOD то срабатывает без ошибки и записывает в эксель но только последнюю строку ето понятно, я так понимаю что надо вогнать данные в массив а потом считывать, вот правда не знаю есть ли такая возможность в abap.

сорри за возможно глупые вопросы
Back to top
View user's profile Send private message
vga
Мастер
Мастер


Age: 75
Joined: 04 Oct 2007
Posts: 1218
Location: Санкт-Петербург

PostPosted: Fri Aug 07, 2009 1:54 pm    Post subject: Reply with quote

elsen wrote:
пример я взял отсюда http://sapnet.ru/viewtopic.php?t=1881 только мне нужна выборка из таблицы поетому изменил вконце код, теперь когда я добавляю CALL METHOD OF EXCEL сап находит первую запись а потом ругается и сообшает что надо перед выгрузкой закрыть селект вобшем тупик.


Думаю проблема в том, что внутри конструкции SELECT ... ENDSELECT, которая неявно использует курсор, нельзя делать RFC вызовы.

Измените код так, как советовал Удав.

Code:
DATA: lt_lfa1 TYPE TABLE OF lfa1.

DATA: wa_lfa1 TYPE lfa1.
DATA: pr_lifnr TYPE lfa1-lifnr,
      pr_name TYPE lfa1-name1,
      pr_ort01 TYPE lfa1-ort01,
      sw_loop TYPE i.

SELECT * FROM lfa1 INTO TABLE lt_lfa1.

LOOP AT lt_lfa1 INTO wa_lfa1.

  pr_lifnr = wa_lfa1-lifnr.
  pr_name = wa_lfa1-name1.
  pr_ort01 = wa_lfa1-ort01.

  CALL METHOD OF excel 'RANGE' = cell EXPORTING #1 = 'A1'.
  SET PROPERTY OF cell 'VALUE' = pr_lifnr.
  FREE OBJECT cell.

ENDLOOP.


логику работы с Excel конечно нужно переделывать, но это уже другой вопрос.
Back to top
View user's profile Send private message Blog Visit poster's website
elsen
Участник
Участник



Joined: 06 Aug 2009
Posts: 17

PostPosted: Fri Aug 07, 2009 2:13 pm    Post subject: Reply with quote

огромное спасибо, тяжело когда кусками изучаеш и основы имеют огромные бреши. все изза недостатка времени, почему в сутках не 48 часов.
Спасибо выручили. Embarassed Very Happy
Back to top
View user's profile Send private message
Удав
Гуру
Гуру


Age: 48
Joined: 25 Jan 2008
Posts: 580
Location: Москва

PostPosted: Fri Aug 07, 2009 2:16 pm    Post subject: Reply with quote

tester wrote:
Конструкции select..endselect

и
select ...into table.
loop at table.
. . .
endloop.

в большинстве случаев сравнимы по производительности,
поэтому именно в этом случае такая замена особого смысла не имеет.

Честно? Smile
А примеры производительности в SE38 когда последний раз смотрели?

Кроме этого, при сложной обработке внутри SELECT .. ENDSELECT возможны случаи, когда обработка падает в дамп из-за слишком долгого выполнения обработки.
+vga правильно сказал про RFC-вызовы.

_________________
С уважением,
Удав.
Back to top
View user's profile Send private message
IP
Участник
Участник



Joined: 31 Mar 2010
Posts: 3

PostPosted: Wed Mar 31, 2010 3:58 pm    Post subject: Всё очень просто :-) Reply with quote

opüiopü

Last edited by IP on Mon Apr 19, 2010 5:08 pm; edited 7 times in total
Back to top
View user's profile Send private message AIM Address
Dmitriy
Аналитик
Аналитик


Age: 47
Joined: 14 Nov 2008
Posts: 300
Location: Russia

PostPosted: Wed Mar 31, 2010 7:01 pm    Post subject: Reply with quote

Удав wrote:
tester wrote:
Конструкции select..endselect

и
select ...into table.
loop at table.
. . .
endloop.

в большинстве случаев сравнимы по производительности,
поэтому именно в этом случае такая замена особого смысла не имеет.

Честно? Smile
А примеры производительности в SE38 когда последний раз смотрели

А зачем? На глазок и так видноSmile
2 tester: насчет оптимизации/производительности вам сюда. А то пацаны-то и не знают про SELECT ... ENDSELECT, как валенки INTO TABLE, а затем LOOP ... ENDLOOP юзают. Laughing
А пока:
Удав wrote:
См. транзакцию ABAPDOCU, раздел "ABAP: Доступы к БД".
Back to top
View user's profile Send private message
IP
Участник
Участник



Joined: 31 Mar 2010
Posts: 3

PostPosted: Fri Apr 16, 2010 5:02 pm    Post subject: Re: Всё очень просто :-) Reply with quote

Code:

*&---------------------------------------------------------------------*
*& Report  ZIP_DATA_TO_EXCEL
*&
*&---------------------------------------------------------------------*
*&
*&
*&---------------------------------------------------------------------*

REPORT  zip_data_to_excel.

include ole2incl. " OLE Automation Controller: OLE Typen

data:   l_ref           type ref to data        ,
          lt_dd02l       type table of dd02l     ,
          h_excel       type ole2_object        , " Excel object
          h_book        type ole2_object        , " Workbook
          h_mapl        type ole2_object        , " list of workbooks
          h_zl             type ole2_object        , " cell

 h_f      type ole2_object        , " font  BOLD   Fett=1, Normal=0
 col      , " color  1=Schwarz, 2=weiss, 3=rot, 4=grün, 5=blau, 6=gelb
 h        type i                  , " meter headline in EXCEL-SHEET
 h2      type i                  , " meter value data in EXCEL-SHEET
 t         type i                  , " meter <table>

        lt_nametab      type table of dntab     ,
        ls_nametab      like line of lt_nametab .


field-symbols: <table> type standard table,
                     <line>  type any                ,
                     <data>                             .

*--- Init color
col = 3. " rot

*--- Selections parameters
parameters:   tabname  type dd03l-tabname obligatory.

*--- Check Table
select tabname from dd02l into table lt_dd02l
  where tabname eq tabname.

if sy-subrc ne 0.
  message i007(e2) with tabname.
  exit.
endif.

*--- Get data
create data l_ref type table of (tabname).
assign l_ref->* to <table>.

select * from (tabname) into table <table> .

*--- Start Excel
create object h_excel 'EXCEL.APPLICATION'.
set property of   h_excel   'Visible' = 1. "#EC NOTEXT " 1 visible / 0 invisible
call method of h_excel 'Workbooks' = h_book.
call method of h_book 'Add' = h_mapl.

call function 'SAPGUI_PROGRESS_INDICATOR'
  exporting
    text   = 'Zeillen in Excel füllen ...'(001)
  exceptions
    others = 1.

*--- Get nametab for headline in EXCEL-SHEET
call function 'NAMETAB_GET'
  exporting
    langu          = sy-langu
    tabname        = tabname
  tables
    nametab        = lt_nametab
  exceptions
    no_texts_found = 1.


*--- Fill headline in EXCEL-SHEET from nametab
clear h.

loop at lt_nametab into ls_nametab.

  h = h + 1.

  if h = 256.
    exit.
  endif.

  call method of h_excel 'Cells' = h_zl
    exporting
    #1 = 1    " Zeile
    #2 = h.   " Spalte

  set property of h_zl    'Value' = ls_nametab-fieldname .  "#EC NOTEXT
  get property of h_zl    'Font'  = h_f.                    "#EC NOTEXT
  set property of h_f     'ColorIndex'   = col .
  set property of h_f     'Bold'  = 1 .     "#EC NOTEXT    " 1 fett / 0

endloop.

*--- Fill value data in EXCEL-SHEET
create data l_ref type (tabname).
assign l_ref->* to <line>.

loop at <table> assigning <line>.

  t = sy-tabix + 1.

  clear h2.

  while sy-subrc = 0.

    h2 = h2 + 1.

    if h2 = 256.
      exit.
    endif.

    assign component sy-index of structure <line> to <data>.
    check sy-subrc = 0.

    call method of h_excel 'Cells' = h_zl
      exporting
      #1 = t      " Zeile
      #2 = h2.    " Spalte

    set property of h_zl    'Value' = <data>.               "#EC NOTEXT
    get property of h_zl    'Font'  = h_f.                  "#EC NOTEXT
    set property of h_f     'ColorIndex'   = col .
    set property of h_f     'Bold'  = 0 .    "#EC NOTEXT   " 1 fett / 0

  endwhile.

  if sy-subrc ne 0.
    sy-subrc = 0.
    continue.
  endif.

endloop.

*--- Disconnect from Excel and save
CALL METHOD OF h_mapl 'SaveAs' EXPORTING #1 = 'C:\test1.xls'.

call method of h_mapl 'CLOSE'.
call method of h_book 'CLOSE'.
call method of h_excel 'QUIT'.
free object h_mapl.
free object h_book.
free object h_excel.
Back to top
View user's profile Send private message AIM Address
IP
Участник
Участник



Joined: 31 Mar 2010
Posts: 3

PostPosted: Fri Apr 16, 2010 5:09 pm    Post subject: Re: Всё очень просто :-) Reply with quote

gsdfgsrdg

Last edited by IP on Mon Apr 19, 2010 5:09 pm; edited 1 time in total
Back to top
View user's profile Send private message AIM Address
Display posts from previous:   
Post new topic   Reply to topic    Russian ABAP Developer's Club Forum Index -> ABAP All times are GMT + 4 Hours
Goto page 1, 2  Next
Page 1 of 2

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


All product names are trademarks of their respective companies. SAPNET.RU websites are in no way affiliated with SAP AG.
SAP, SAP R/3, R/3 software, mySAP, ABAP, BAPI, xApps, SAP NetWeaver and any other are registered trademarks of SAP AG.
Every effort is made to ensure content integrity. Use information on this site at your own risk.