sap ole что это
Подход к реализации больших форматированных отчетов в SAP BW
На проектах внедрения отчетности с использованием хранилища данных SAP BW многим архитекторам и консультантам приходится решать задачи подготовки больших форматированных отчетов: разнообразных ведомостей, выписок и т.п. Такие отчеты обычно характеризуются:
Консультантом создается рабочая книга BW-BEx, которая содержит один или несколько BW-BEx-отчетов. Отчеты выгружаются на отдельные листы этой книги, которые обычно скрывают от пользователей. Видимым оставляют лишь один лист книги, содержащий целевую форму отчета с необходимым форматированием.
Работа пользователя с таким отчетом выглядит следующим образом:
Чего только не придумывают консультанты, чтобы, оставаясь в рамках стандартного подхода, качественно сделать-таки большой отчет. Но почти всегда ничего не получается. «Почти» означает компромиссы, послабления в требованиях. Бизнес-пользователи либо соглашаются применять более ограничивающие фильтры и отчет возвращает меньше данных, либо ждать выполнения подольше, либо вручную сводить несколько фрагментов отчета в один.
Чтобы все-таки не говорить клиенту «нет, мы не можем этого реализовать при таких требованиях», необходимо для начала сделать правильные выводы из очевидного: каждый инструмент предназначен для своей задачи.
Инструменты BW BEx Analyzer и SBOP Analysis for Office в общем случае не предназначены для реализации эффективных отчетов с большим количеством ячеек, с числом около 750000 и более (см SAP-ноту 1040454). Поэтому, используя модель данных SAP BW, надо выбрать другой инструмент, другой подход в реализации. Тогда решение не только обязательно получится, но и будет при этом эффективным.
Последние версии SAP Netweaver, SAP BW и HANA внесли большее разнообразие подходов публикации BW-данных в Excel, без использования BW BEx. Можно упомянуть такие:
Я хочу рассказать о подходе, гораздо менее требовательном к новизне версий используемых продуктов, и в чем-то менее сложным. Речь идет о публикации данных отчетов в шаблон Excel-документа через OLE-интерфейс. Excel-шаблон при этом хранится в репозитории BDS на стороне SAP BW.
Преимущества подхода с OLE очевидны:
Сложности в ABAP могут возникнуть при получении данных из модели BW. Возможные варианты: вызов BEx-отчета в ABAP, вызов FM RSDRI_INFOPROV_READ, SQL-SELECT по таблицам модели данных. Но это обычно есть в арсенале навыков опытного BW-консультанта. Глубокие знания программировании ABAP понадобятся, если возникнет потребность еще более ускорить работу кода по подготовке данных за счет тюнинга ABAP-программы или даже распараллеливания вычислений. Последнее, кстати, невозможно архитектурно в подходе с рабочими книгами BW BEx.
Вкратце, порядок создания отчета с использованием подхода с OLE следующий.
Sap ole что это
Часовой пояс: UTC + 3 часа
Правила форума
OLE vs DOI
Специалист |
Зарегистрирован:
Пт, апр 07 2006, 22:15
Сообщения: 184
Коллеги, проучаствуйте в дискурсе, кто в хорошем понимании взаимодействия с Excel. Есть два отчета с выгрузкой в Excel со сложным форматированием, форматирование в первом делается с помощью макросов, форматирование во втором делается с помощью методов OLE. Что быстрее? |
Специалист |
Зарегистрирован:
Чт, ноя 20 2008, 16:29
Сообщения: 245
Откуда: RU->DE
Пол: Мужской
Почетный гуру |
Зарегистрирован:
Чт, авг 19 2004, 17:37
Сообщения: 1962
Откуда: Москва
Пол: Мужской
Макросы быстрее! Чем реже вызываются функции OLE и больше объем переданных данных за один вызов, тем лучше! А что за сложные формы, если не секрет? |
Младший специалист |
Зарегистрирован:
Пт, окт 31 2008, 15:58
Сообщения: 70
отходит от темы. Единственный плюс OLE перед макросами, которой гипотетически может быть, это если нам нужно перелопатить огромный массив данных, и он будет меняться в зависимости от того, что мы уже выгрузили. Чтобы производительность сервера перекрывала коммутационных временные затраты. Но если честно, сложно придумать даже такое, потому как проще будет разбить тогда на 2 последовательные выгрузки. Намного интереснее вопрос напрямую: технология OLE vs DOI. document_type = ‘Excel.Sheet.8’. CALL METHOD document->create_document Мне больше нравится OLE2. Потому как порой я не знаю, есть ли нужный мне метод, т.е. если я не нашел его в списке, может он не так называется, или это можно реализовать через другой. А в ole, что пишу в макросе, то можно и в abap перевести. Каркас я обычно строю не на макросах. _________________ Часовой пояс: UTC + 3 часа Кто сейчас на конференцииСейчас этот форум просматривают: нет зарегистрированных пользователей |
Вы не можете начинать темы Вы не можете отвечать на сообщения Вы не можете редактировать свои сообщения Вы не можете удалять свои сообщения Вы не можете добавлять вложения |
Логотип © 2006 Андрей Горшков
Поддержка: Кирилл Андреев, 2011-…
Manipulate Excel with OLE & ABAP
I recently got involved with a project where the user wanted to update an existing Excel spreadsheet automatically via an ABAP program. I started digging in and found that this could be accomplished using OLE technology. This weblog gives an small example application which any beginner could use to get their application started.
ABAP Source Code
data: e_sheet type ole2_object.
data: e_appl type ole2_object.
data: e_work type ole2_object.
data: e_cell type ole2_object.
data: field_value(30) type c.
parameters: p_file type localfile default ‘C:RichTest.xls’.
* Start the application
create object e_appl ‘EXCEL.APPLICATION’.
set property of e_appl ‘VISIBLE’ = 1.
call method of e_appl ‘WORKBOOKS’ = e_work.
call method of e_work ‘OPEN’
exporting #1 = p_file.
* Write data to the excel file
shift field_value left deleting leading space.
concatenate ‘Cell’ field_value into field_value separated by space.
* Position to specific cell in Column 1
call method of e_appl ‘Cells’ = e_cell exporting #1 = sy-index #2 = 1.
* Position to specific cell in Column 2
call method of e_appl ‘Cells’ = e_cell exporting #1 = sy-index #2 = 2.
call method of e_work ‘close’.
call method of e_appl ‘QUIT’.
free object e_appl.
Result
For more information on ABAP/OLE, search on “OLE” in the ABAP forum and check out this great article called An Easy Reference For OLE Automation by Serdar Simsekler. This guide will go over more advanced topics and has a lot more code samples.
Assigned Tags
Nice one.. Any idea of some more blogs about the usage of the SAP ActiveX controls like Tabstrip, Tree with office tools?
By the way, does anybody have an idea for protecting a cell in excel. I’ve been trying many methods by suggestion with object programming in VB but with no success.
Help would be great.
Thanks a lot
Great article, but just a quick question
Do you have to explicitly save the spreadsheet or should the ‘close’ statement take care of this.
I ask only as I have tried to implement the code & I get a popup asking to save the spreadsheet
If I add ‘call method of workbook ‘SAVE’.’ to my logic, the abap finishes with the spreadsheet still open & not saved. Could this be something to do with the windows security employed at my client site.
I try to run your coding and the coding didnt work.
I run it and the spreadsheet display out a while without data and close immediately. Why this can be happened?
The microsoft office I am using is 2003.
I know why it is not working.
I need to create the excel file at the very first before I can successfully run the program.
It there possible that the program can automatically generate the excel file at the same time?
Great blog! It was certainly useful as I’m a beginner to all these OLE stuff.
However, could you please provide some help for the following? I now have a requirement to generate random numbers in a certain range of cells within the Excel spreadsheet.
I have looked through the different methods and believe that I should be using the Randomize and Rnd methods, but I’m not exactly sure as to how it should be coded. Could you please help me out?
Also, the link that you gave for the article «An Easy Reference for OLE Automation» doesn’t seem to exist anymore. Do you have the new link?
Thanks for your help!
***** I’d like to copy sheet(1) format to sheet(2) here ******
Please help me out!!
Thanks & Best Regards,
Eunice
data: e_sheet type ole2_object.
data: e_appl type ole2_object.
data: e_work type ole2_object.
data: e_cell type ole2_object.
data: field_value(30) type c.
itab-field1 = ‘ROHIT1’.
itab-field2 = ‘ROHIT2’.
append itab.
itab-field1 = ‘ROHIT3’.
itab-field2 = ‘ROHIT4’.
append itab.
itab-field1 = ‘ROHIT5’.
itab-field2 = ‘ROHIT6’.
append itab.
itab-field1 = ‘ROHIT7’.
itab-field2 = ‘ROHIT8’.
append itab.
DATA wa like itab.
DATA : field1 like itab-field1,
field2 like itab-field2.
* Start the application
create object e_appl ‘EXCEL.APPLICATION’.
set property of e_appl ‘VISIBLE’ = 1.
* Open the file
call method of e_appl ‘WORKBOOKS’ = e_work.
call method of e_work ‘OPEN’
EXPORTING
#1 = p_file.
get property of e_appl ‘ActiveSheet’ = e_sheet.
* open the worksheet
call method of e_appl ‘WORKSHEETS’ = e_sheet
EXPORTING
#1 = 1.
call methoD of e_sheet ‘ACTIVATE’.
* set worksheet name
set property of e_sheet ‘NAME’ = ‘rowdata’.
* Write data to the excel file
loop at itab into wa.
* Create the value
field1 = wa-field1.
field2 = wa-field2.
* Position to specific cell in Column 1
call method of e_appl ‘Cells’ = e_cell
EXPORTING
#1 = sy-index
#2 = 2.
set property of e_cell ‘Value’ = field1.
* Position to specific cell in Column 2
call method of e_appl ‘Cells’ = e_cell
EXPORTING
#1 = sy-index
#2 = 3.
* Set the value
set property of e_cell ‘Value’ = field2.
* Close the file
call method of e_work ‘close’.
* Quit the file
call method of e_appl ‘QUIT’.
Using ole2 objects to create an excel file
Let’s see how to create a lovely excel sheet like this using ole2 objects: 😀
First you need to know the different parts in MS excel. Each part will represent an ole2 object in our program:
All the examples below use the following template report. You only need to copy the code on the example and paste it in the space reserved for this purpose.
In this report you can see how to create a new document, how to save it and how to close it.
DATA : lo_cellstart TYPE ole2_object,
lo_cellend TYPE ole2_object,
lo_selection TYPE ole2_object,
lo_validation TYPE ole2_object.
DATA : lv_selected_folder TYPE string,
lv_complete_path TYPE char256,
lv_titulo TYPE string.
CONCATENATE lv_selected_folder ‘\Test’ INTO lv_complete_path.
Select a cell |
---|
Change the name of the Worksheet |
---|
SET PROPERTY OF lo_worksheet ‘Name’ = ‘Hello!’. |
Modifying the content
I think the best way to understand how it works is creating a macro in excel and seeing the Visual Basic code in order to “translate” it to abap.
For create a macro you need first to activate the developer tab, the following link explains how to do it:
Create a macro is easy, you can follow the following link:
I also recommend to download the VB language reference as guide.
Compare the VB code with the Abap code. And you will understand how it works. You don’t need to transform the entire VB code in Abap in all the cases, only the parts you need.
1 – Select a cell and set a Value:
2- Change Font and Size
3- Change Colour, Bold, Underline and Italics:
In this example you can see we are using the VB constant xlUnderlineStyleSingle with the value 2. To know the values of those constants in excel you can download the VBA language reference from the link http://msdn.microsoft.com/en-us/library/aa220733(v=office.11).aspx and follow the following path for see all the constants. Or also you can use this link to look up the constants values online http://msdn.microsoft.com/en-us/library/aa221100(v=office.11).aspx.
But I prefer to execute the macro recorded step by step for debug the code and you can see the value of the constants you want leaving the mouse cursor over that constant.
Abap | |||
---|---|---|---|
Abap | ||
---|---|---|
Copy-Paste | |
---|---|
Test report: Example of use the include ZRIC_OLE2_UTILS |
---|
Code of include ZRIC_OLE2_UTILS |
---|