Выгрузка в word abap

Обновлено: 06.07.2024

Символьные данные (также называемые строковыми) относятся к объектам данных широких символьных типов (включая типы C, N, D, T и String). Для строковых данных ABAP предоставляет некоторые уникальные операторы операций, эти операции не выполняют преобразование типов при обработке объектов данных и рассматриваются как типы C.

2. Обработка строковых данных

1. Подключите строку, используйте CONCATENATE
CONCATENATE s1 . sn INTO s_dest [SEPARATED BY sep].

Этот оператор соединяет строки s1 . sn и присваивает результат s_dest, где s_dest также может быть переменной в s1 . sn. Опция SEPARATED BY используется для указания строки в качестве разделителя, которая вставляется между s1 . sn при формировании новой строки. Если длина после соединения превышает заданную длину целевых данных, усечение присваивается c. Если результат усечен, SY-SUBRC возвращает 4, в противном случае значение возвращает 0. Чтобы избежать усечения, вы можете определить c как строку, а длина этого типа является адаптивной.

6010417-dbaf52844fc61b88.jpg

2. Разбейте строку и используйте SPLIT
SPLIT s_source AT sep INTO s1. sn.

Это предложение ищет разделитель sep в исходной строке и разбивает мета-строку на маленькие строки в соответствии с разделителем и помещает их в поле назначения s1 . sn. Эти подстроки не включают разделитель. С типом оператора соединения, если результат усечен, SY-SUBRC возвращает 4, в противном случае значение возвращает 0. Если исходная подстрока может разбить больше указанного числа подстрок, последняя оставшаяся часть исходной подстроки, включая следующие разделители, будет записана в последнюю подстроку. Чтобы избежать этой ситуации, необходимо использовать внутреннюю таблицу для работы.
SPLIT s_source AT sep INTO TABLE itab.

Оператор LOOP AT используется для циклического вывода каждой строки данных во внутренней таблице.

6010417-9571d2214be80b3e.jpg

3. Найдите шаблон подстроки
Чтобы найти шаблон подстроки в строке, используйте SEARCH утверждение
SEARCH c FOR str.

Измените предложение, чтобы найти строку str в поле c. Если найдено, верните SY-SUBRC в 0, SY-FDPOS вернет позицию строки в поле c (смещение в байтах от вычисления), в противном случае верните SY-SUBRC в 4. Так называемый шаблон означает, что искомая строка может не совпадать со строкой. Вы можете задать игнорирование или оставить пробел в конце строки, или использовать подстановочный знак «*» для расширения гибкости поиска. Существует несколько режимов:

  • str искать str и игнорировать конечные пробелы
  • .str. Поиск по ул., но не игнорируйте конечные пробелы
  • * str Поиск слов, заканчивающихся на str
  • str * Поиск слов, начинающихся с str

6010417-75956363dfeee4a6.jpg

4. Чтобы заменить содержимое поля, используйте оператор REPLACE.
REPLACE str1 WITH str2 INTO s_dest [LENGTH len].

Этот оператор ищет поле s_dest, и если в нем появляется строка str1, замените первое вхождение на str2. Если длина не указана, ищется весь s_dest. Если указана длина len, будет выполняться поиск только первых байтов len. Если поле SY-SUBRC возвращает 0, это означает, что оно было заменено, а не ноль означает, что оно не было заменено.

6010417-f1612d6b5bfa969c.jpg

5. Определите длину поля, исключая завершающие пробелы, используйте STRLEN, оператор обрабатывает операнд str как символьный тип данных, независимо от фактического типа, и без преобразования
[COMPUTE] n = STRLEN( str ).

6010417-7a2bfcb6ac3262dd.jpg

  • SHIFT Сдвиг всей строки или подстроки
  • CONDENSE удалить лишние пробелы в строке
  • Перевести преобразование символов, таких как преобразование ABC в ABC
  • CONVERT TEXT создает сортируемый формат
  • OVERLAY Наложение одной строки на другую строку
  • Когда назначается WRITE TO, тип объекта данных будет игнорироваться и обрабатываться как данные типа символа

3. Сравнение данных персонажа

Символьные логические выражения используются для определения отношения локализации между двумя строками

оператор смысл
s1 CO s2 Если s1 содержит только символы в s2, логическое выражение истинно
s1 CN s2 Если s1 содержит символы, отличные от s2, логическое выражение истинно
s1 CA s2 Если s1 содержит любой из символов в s2, логическое выражение истинно
s1 NA s2 Если s1 не содержит символов s2, логическое выражение имеет значение true
s1 CS s2 Если s1 содержит строку s2, логическое выражение истинно
s1 NS s2 Если s1 не содержит строку s2, логическое выражение имеет значение true
s1 CP s2 Если s1 содержит шаблон s2, логическое выражение имеет значение true
s1 NP s2 Если s1 не содержит шаблон s2, логическое выражение имеет значение true

CO, CN, CA, NA чувствительны к регистру при сравнении, а конечные пробелы также находятся в пределах диапазона сравнения: при использовании CS, NS, CP, NP пробелы в конце игнорируются, а сравнение нечувствительно к регистру. После сравнения, если результат равен true, системное поле SY-FDPOS выдаст информацию о смещении s2 в s1.

6010417-8ea63d185434d487.jpg

3 Операция позиционирования подстроки

Используйте только указанную часть подстроки. s [+o][(1)]
Его смысл состоит в том, чтобы выполнять операторную операцию над частью поля s, начиная с o-й позиции (смещение от 0) и имея длину 1. Если длина не указана, обрабатываются все биты между oth и концом поля s.

6010417-ce31ab81d9a3771b.jpg

Как правило, смещение и длина должны быть указаны как числа без знака. Тем не менее, переменные могут быть определены динамически в следующих ситуациях:

  • При присваивании значений полям с помощью операторов MOVE или операторов присваивания
  • При использовании оператора WRITE TO для переноса значений в поле
  • При назначении полей символам поля с помощью ASSIGN
  • При использовании PERFORM для передачи данных в подпрограмму

Имеет смысл указать смещения для типов символов, числовых текстовых полей, шестнадцатеричных полей и полей даты и времени, не используйте указанные смещения для числовых полей типов F, I и P.

Интеллектуальная рекомендация


Michael.W Поговорите о Hyperledger Fabric. Проблема 20 - Подробная индивидуальная сортировка узла с пятью порядками с исходным кодом для чтения.

Michael.W Поговорите о Hyperledger Fabric. Проблема 20 - Подробная индивидуальная сортировка узла с пятью порядками с исходным кодом чтения Fabric Файл исходного кода одиночного режима находится в ord.


Мяу Пасс Матрица SDUT

Мяу Пасс Матрица SDUT Time Limit: 1000 ms Memory Limit: 65536 KiB Submit Statistic Problem Description Лянцзян получил матрицу, но эта матрица была особенно уродливой, и Лянцзян испытал отвращение. Чт.


Гессенская легкая двоичная структура удаленного вызова

Hessian - это легкая двоичная структура удаленного вызова, официальный адрес документа, в основном он включает протокол удаленного вызова Hessian, протокол сериализации Hessian, прокси-сервер клиента .


TCP Pasket и распаковка и Нетти Solutions

Основные введение TCP является ориентированным на соединение, обеспечивая высокую надежность услуг. На обоих концах (клиенты и терминалы сервера) должны иметь один или более гнезда, так что передающий.

This document gives a brief introduction about its usage and could be used as a starting point to build your own application which needs to manipulate word document via ABAP.

For example, I create a very simple word document which contains a header area, a paragraph with three lines as body, and a picture.

/wp-content/uploads/2014/05/clipboard1_461558.jpg

The most efficient way to study is create a word document by yourself, change extension to zip and explore it.

/wp-content/uploads/2014/05/clipboard2_461559.jpg

I use the following sample code to explain how to use this class.

Comments

The returned data has xml format( so does all the left other kinds of parts in this document ) so it could be easily parsed via DOM or SAX parser.

/wp-content/uploads/2014/05/clipboard3_461560.jpg

3. from document instance we can get main part instance. Its binary data includes all the three body line texts with their font color:

/wp-content/uploads/2014/05/clipboard4_461561.jpg

/wp-content/uploads/2014/05/clipboard5_461562.jpg

4. The binary data of all pictures embedded in the word document could be retrieved via two steps. Firstly get the image part collection from main part instance and then loop each image part instance from the image collection. The get_part method accepts the index starting from 0. The way to read header block information is exactly the same.

You could also achieve the same requirement with the respective class below.

/wp-content/uploads/2014/05/clipboard6_461564.jpg

If you would like to know how a word template is merged with data from xml file ( for example a response file from web service ), you can find technical detail in my blog Understand how the word template is merged with xml data stream .

Last month, i published my abstraction class to manage Word OLE link. It can generate complete (and complex) word document, but it is a little slow for big tables.

I updated my abstraction class to generate DOCX file from ABAP directly, without any OLE usage. I know there are actually some projects that want to do that (abap2docx for example). But i think theses projects are too complex to use, or not yet usable in the true life.

With my class, it never be easier to generate DOCX. You never have to use or understand XML.

docx_generation-sap-abap-hello-world[1].jpg

The class is simple, but can manage complex documents !

Here is the feature list :

In the download file, you will find a test program that contain the class CL_WORD and a demo of how to use it. You will find also some images and 1 template. Theses files are used by the test program, but are not necessary for the class itself.

Feel free to comment here 🙂

My others blogpost :

Assigned Tags

docx_generation-sap-abap-hello-world[1].jpg

ABAP2XLSX is fine you don't know anything about XML 🙂 Unfortunetly ABAP2DOCX seems to be in hibernation.

As all your other projects are really great I will give it a try for sure!

Right click and copy the link to share this comment

Hope you could find it usefull

Right click and copy the link to share this comment

Will there be a separate class? I guess this would be more reuseable.

And sad to say that, but the generated docs file cant be opened with Word 2010

Right click and copy the link to share this comment

Have you chaanged the path of image/template to appropriates ones on your computer ?

I think the generated word file dont use the template 😉

If everything is ok in the demo program and there is the error, could you please expend the word error popup and write me the exact error message please ? And also send me the generated word file ?

Right click and copy the link to share this comment

About the separate class:

For a customer development, i always use separated class (SE24).

But for tools i share with other people, i find it more simple to use an include SE38. Easier to read, only 1 object to transfer.

You could easily recreate a class if you require it, but which usage require SE24 class instead of embedded one ? (just remove "demo" code and you could use the class as an "include" in any program)

In next release i will separate demo code and class code.

Right click and copy the link to share this comment

You can take the new 1.1 version where the class is in a separate include file.

Right click and copy the link to share this comment

Many thanks for ZTOAD. Simply an awesome tool to use.

Quick question! I have downloaded this utility but it has a file ZTEST_DOC.slnk. How to load it in SAP?

Right click and copy the link to share this comment

Thank you Ahmed, i like it too 😀

For .slnk, just use saplink, it is same as .nugg but with only 1 object inside (a little smaller and a little faster for me to generate)

Right click and copy the link to share this comment

I just did. But it says

Start import of nugget

/wp-content/uploads/2015/11/cl_word_832428.jpg

Nothing below that. Please find attached.

Right click and copy the link to share this comment

/wp-content/uploads/2015/11/cl_word_832428.jpg

Another thing. When I choose Display Nugget. It says Empty Nugget.

Right click and copy the link to share this comment

yes, its not a nugget but a slinkee file. Dont you have a second tab for slinkee files in your version of saplink ?

Right click and copy the link to share this comment

Oops! My bad. Truly an honest mistake. I just ignored that tab.

Right click and copy the link to share this comment Right click and copy the link to share this comment

it take many years before I use it 😉

Right click and copy the link to share this comment

Another great piece of code.. thank you.

Right click and copy the link to share this comment

This is fantastic.

Do you see this as a possible replacement for SMARTFORMS/SAPSCRIPT in some cases? You would create a word template with your logo and the general format and then use SAP to dynamically fill the business data?

PS ABAP2XLS is used in real life at my company, but I have wrapped around it several helper classes to make it easy for our developers to use.

Right click and copy the link to share this comment

My remark about real life usage concern only DOCX generation 🙂

If abap2docx was as wonderfull as abap2xls, my tool never be born 😉

regarding your question about smartform/sapscript replacement. If the user requirement is to have DOCX file, yes i think you can replace smartforms. Create the word template with all header/footer, and all styles you need. You could also insert all image you will need.

Remember that actual class drop existing document content, so you have to write all pages in program. But if required, it is very easy to change the class to add an option to keep actual text content of the template. (edit : Done for the next release)

For example, if you have only individual fields to fill, you can create a complete docx into word, replace all variable part with word custom fields. And with the class you just have to define custom fields value 🙂

Right click and copy the link to share this comment

I have a Customer requirement like this.. I need Show a Word templete with header, logo, footer and more thing like a Smartforms with an ABAP program.

Right click and copy the link to share this comment

May you please elaborate on your helper class? (What exactly does it do?)

Wouldn't it be useful to enrich the original project with it?

Right click and copy the link to share this comment

When the ABAP2XLSX project was on the SCN code exchange I found it really easy to contribute, and I was right up there on the leader board of active contributors.

I have to say I am struggling with the environment where the project is hosted now, as I think other people are - because I think the project has totally stalled since it moved. I could be looking in the wrong place but there does not seem to have been any activity for months.

In any event I have a helper class where I store the code that does not change between different ALV reports. I call a method of the helper to change the ALV object into an ABAP2XLSX object, then the program at hand makes application specific changes, and then another method of the helper sends the modified EXCEL object as an email.

There is more detail on this in chapter 11 of my good old book. Moreover, if you got to the SAP Press Website and look up my book you can download the associated materials for free, and their you will find class ZCL_EXCEL_EMAILER and some of it's friends, which are my helper classes. Looking at the code I just noticed it still has a BREAK HARDYP in it, oh well, too late now.

The code has lots of comments but they say WHY things are done, not how, as the ABAP2XLS methods are so well named it is obvious what they do i.e. you don't have to think too hard what a method call like WORKSHEET->FREEZE_PANES does.

I asked my editor why SAP Press let people download supplementary material for their books for free, and she said having some sort of secret code you get with each book was just too much extra effort for no real benefit. In fact when people download such things they are often so intrigued by the content (code) they end up buying the book anyway.

Использование программирования ABAP для работы с документами Microsoft Office Word

SAP ABAP предоставляет стандартный класс CL_DOCX_DOCUMENT, который обеспечивает локальные операции чтения и записи текстовых документов Microsoft Office, заканчивающихся на «.docx».

В этой статье описывается простое использование класса ABAP CL_DOCX_DOCUMENT.


Начиная с Microsoft Office 2007, когда мы создали новый текстовый документ, его расширение изменилось с «.doc» на «.docx», что основано на спецификации открытого исходного кода: формат Office openXML.

Например, на рисунке ниже я создал простой текстовый документ, который содержит область заголовка, абзац, состоящий из трех строк цветного текста, и изображение.


Мы сохраняем этот документ локально, меняем его расширение с .docx на .zip, а затем дважды щелкаем, чтобы открыть его с помощью программы распаковки, такой как winrar.

Итак, я обнаружил, что этот простейший документ Word на самом деле состоит из очень многих XML и папок.


Пример кода выглядит следующим образом:

1. Передайте двоичное содержимое документа word в метод cl_docx_document => load_document, чтобы получить ссылку на объект документа, и затем вы можете использовать ссылку на объект для вызова различных методов.

2. Создатель слова document, время создания, время последней модификации и другая информация хранятся в так называемой «Базовой части свойства», вы можете получить ссылку на «Базовую часть свойства» через метод lo_document-> get_corepropertiespart, а затем использовать эту ссылку для вызова метода. get_data получает фактический контент.

На следующем рисунке показан пример содержимого, возвращаемого get_data, который можно увидеть в формате xml.


3. Теперь мы готовы прочитать текст слова документа. Используйте метод lo_document-> get_maindocumentpart, чтобы получить текст документа word, также включены тип шрифта и цвет текста. Как показано ниже:



4. Конечно, двоичное содержимое картинок, вставленных в документ Word, также можно прочитать. Использование: lo_image_parts-> get_part возвращает.

Исходя из этой же идеи, другие форматы офисных документов после Microsoft Office 2007, такие как Powerpoint и Excel, следуют стандарту Office OpenXML, поэтому вы также можете увидеть множество xml и папок после изменения имени суффикса на .zip. ABAP также предоставляет стандартные коды для чтения и записи этих документов Office, такие как CL_PPTX_DOCUMENT, CL_XLSX_DOCUMENT и т. Д., Как показано ниже.



Чтобы узнать больше о технических статьях Джерри, пожалуйста, обратите внимание на публичный номер "Wang Zixi" или отсканируйте QR-код ниже:

Читайте также: