Заполнение шаблона word qt
I want to use QAxObject to create a new docx file. how can I create a new doc and docx file and write my text with QAxObject in qt for windows. I try this code but I could not find my answer because it opens existing file but I want to create new one and use QAxObject .
you need to clarify your question and show what you already had tried by yourself. Because there are a lot of possible answers and a lot of job should be done. Don't write that you are doing something, show what you already did and ask more detailed questions.
Please, update your question to have all necessary information. It is not welcome if you are pushing everyone to visit external links. Second point, stackoverflow is not a free-coding-service, you need to to self investigation of your question and show summarized results to community.
@DmitrySazonov: I understand the question perfectly: How to use ActiveQt to create a word document from scratch?, as opposed to opening / reading an existing document.I can't find a single template / example / tutorial on SO or any other forum that answers that question, and upvotes here show that some other people wants this question to be answered. Please reopen!
2 Answers 2
There are already some answers to questions like this one in SO suggesting the usage of QAxObject with dynamicCall() for MS Office automation. This can be done, and it will work, but I think that there is a better and more fun way to do it.
This is very similar to the Qutlook Example for the Outlook application that is included among the ActiveQt samples. The documentation doesn't tell much more than adding the TYPELIBS variable in your application's .pro file. The translation is performed by the dumpcpp.exe utility that may be found in the Qt bin directory. This is a simple command line program project importing the MS Word object model:
To discover the GUID of other type libraries, you may use the oleview.exe utility.
QMake creates a source file MSWORD.cpp and a header MSWORD.h that you may include in your own classes to access to the generated object model. This sample generates a Word document from scratch, and saves it in two formats:
Поскольку отчет должен быть сгенерирован в последнем элементе, я проверил информацию в Интернете. Поскольку VB не может его понять, здесь не так много сводок. В реализации не используется метка, но курсор вставляется в позицию курсора, включая: создание файла, набор текста, добавление текста , Добавить изображения, добавить таблицы, добавить текст (изображения) в таблицы, переместить курсор в конец, переместить курсор (аналогично вкладке) и т. Д.
Добавить QT + = axcontainer
QAxObject * m_pWord; // Указываем на все приложение Word
QAxObject * m_pWorkDocuments; // Укажите на набор документов, в Word много документов
QAxObject * m_pWorkDocument; // Укажите на документ, соответствующий m_sFile, который является документом для работы
void MainWindow::open()
m_pWord = new QAxObject();
bool flag = m_pWord->setControl( "Word.Application" );
if(!flag)
return;
>
m_pWord->setProperty("Visible", true);
QAxObject *document = m_pWord->querySubObject("Documents");
if(!document)
return ;
>
// Получить текущий активированный документ
m_pWorkDocument = m_pWord->querySubObject("ActiveDocument");
>
/*
* Метод набора
* Вертикально, горизонтально
*/
void MainWindow::setype(bool type)
QAxObject* selection = m_pWord->querySubObject("Selection");
if(!selection)
return;
>
if(type)
selection->querySubObject("PageSetup")->setProperty("Orientation","wdOrientLandscape");
>else selection->querySubObject("PageSetup")->setProperty("Orientation","wdOrientPortrait");
>
>
/*
* Получить ширину страницы
*/
int MainWindow::pageWidth()
int width;
QAxObject* selection = m_pWord->querySubObject("Selection");
if(!selection)
return;
>
width = selection->querySubObject("PageSetup")->property("PageWidth").toInt();;
return width;
>
/*
* Установить размер шрифта
*/
void MainWindow::setFontSize(int size)
QAxObject* selection = m_pWord->querySubObject("Selection");
if(!selection)
return;
>
selection->querySubObject("Font")->setProperty("Size",size);
>
void MainWindow::setAlignment(int index)
QAxObject *selection = m_pWord->querySubObject("Selection");
if(!selection)
return;
>
if(index == 0)
selection->querySubObject("ParagraphFormat")->setProperty("Alignment","wdAlignParagraphCenter");
>
if(index == 1)
selection->querySubObject("ParagraphFormat")->setProperty("Alignment","wdAlignParagraphJustify");
>
if(index == 2)
selection->querySubObject("ParagraphFormat")->setProperty("Alignment","wdAlignParagraphRight");
>
if(index == 3)
selection->querySubObject("ParagraphFormat")->setProperty("Alignment","wdAlignParagraphLeft");
>
>
void MainWindow::typeText(QString text)
QAxObject* selection = m_pWord->querySubObject("Selection");
if(!selection)
return;
>
selection->dynamicCall("TypeText(const QString&)",text);
>
/*
Вставить картинку
*/
void MainWindow::AddPicture(QString file)
QAxObject* selection = m_pWord->querySubObject("Selection");
if(!selection)
return;
>
QString filename = file;
filename.replace("/","\\");
QAxObject *Inlineshapes = selection->querySubObject("InlineShapes");
Inlineshapes->dynamicCall("AddPicture(const QString&)",filename);
delete Inlineshapes;
>
/*
Вставить возврат каретки
*/
void MainWindow::insertEnter()
QAxObject* selection = m_pWord->querySubObject("Selection");
if(!selection)
return;
>
selection->dynamicCall("TypeParagraph(void)");
>
/*
* Переместите курсор в конец и выйдите из ячейки
*/
void MainWindow::moveForEnd()
QAxObject* selection = m_pWord->querySubObject("Selection");
QVariantList params;
params.append(6);
params.append(0);
selection->dynamicCall("EndOf(QVariant&, QVariant&)", params).toInt();
>
/*
Создать форму
QStringList headList Добавить заголовок
*/
QAxObject* MainWindow::createTable(int row, int column,QStringList headList)
QAxObject* selection = m_pWord->querySubObject("Selection");
if(!selection)
return false;
>
selection->dynamicCall("InsertAfter(QString&)", "\r\n");
QAxObject *range = selection->querySubObject("Range");
QAxObject *tables = m_pWorkDocument->querySubObject("Tables");
QAxObject *table = tables->querySubObject("Add(QVariant,int,int)",range->asVariant(),row,column);
Таблица-> setProperty («Стиль», «Тип сетки»);
// Таблица автоматически растягивает столбцы 0 фиксированный 1 Скорректированный в соответствии с содержимым 2 Скорректированный в соответствии с окном
table->dynamicCall("AutoFitBehavior(WdAutoFitBehavior)", 2);
// Устанавливаем заголовок
for(int i=0;i
// Жирный
table->querySubObject("Cell(int,int)",1,i+1)->querySubObject("Range")->dynamicCall("SetBold(int)", true);
>
return table;
>
void MainWindow::setCellText(QAxObject *table, int row, int column, QString text)
QAxObject* range = table->querySubObject("Cell(int, int)",row+1,column+1)->querySubObject("Range");
if( range)
return;
>
/*
Вставить картинку в таблицу
*/
void MainWindow::setAddPicture(QAxObject *table, int row, int column, QString picPath)
QAxObject* range = table->querySubObject("Cell(int, int)",row+1,column+1)->querySubObject("Range");
if(!range)
return;
>
range->querySubObject("InlineShapes")->dynamicCall("AddPicture(const QString&)",picPath);
>
/*
Курсор подпрыгивает, как на вкладке в таблице.
*/
void MainWindow::moveRight()
QAxObject* selection = m_pWord->querySubObject("Selection");
if(!selection)
return;
>
selection->dynamicCall("MoveRight(int)",1);
>
void MainWindow::Example()
QStringList header;
NewTable (1,2, header); // Создаем таблицу
TypeText (tr (" 1")); // Добавляем текст
insertEnter (); // Новая строка
insertText("");
AddPicture ("Изображение 1"); // Вставляем картинку
MoveRight (); // Вставляем курсор в следующую ячейку
TypeText (tr (" 2"));
insertEnter();
insertText("");
AddPicture («Изображение 2»);
Согласно предыдущей главе, пришло время закончить ерунду и перейти непосредственно к теме:
Как следует из названия, эта статья впервые представляет QAxwidget для управления офисом и PDF
QAxwidget, который является qt-версией элемента управления ActiveX, который удобен для вызова и отображения в программе qt и может напрямую вызывать компонент com. О введении QAxwidget на официальном сайте есть более подробная информация, вы можете проверить это сами:
Введение в официальный сайт QAxwidget
Кроме того, цитирование изображения других может лучше понять структуру наследования:
Портал
Среда разработки: windows7 + vs2013 + qt5.4 (32-разрядная версия).
Если вы используете QAxwidget только для открытия PDF-файла, это относительно просто, и в этой области есть больше примеров, но в основном это мелко, нет более глубокого контента, к сожалению, я также, если вам нужен подробный API, вам нужно перейти непосредственно В поисках API компонента COM, но я смотрел только API в PDF.
При использовании QAXwidget для работы с офисным файлом компьютер должен быть оборудован офисом. Может использоваться Office2007 и выше (не пробовал 03, неизвестно). В то же время, если qt5.7 должен вызвать dilaog, чтобы открыть файл для отображения эффекта, если он загружен напрямую, эффект примерно равен Жук.
Подготовка: Чтобы использовать QAxwidget, вам нужно добавить библиотеку:
2. Открыть в соответствии с выбранным файлом:
3. Он открывается, и эффект выглядит следующим образом (игнорировать содержимое документа word, содержимое предыдущего блога):
4、Следует отметить, что после его использования не забудьте закрыть его, в противном случае файл open word.exe все еще находится в процессе.
На самом деле, это похоже на открытие PDF-файла. После отказа от офисного файла я решил открыть PDF-файл.
Обратите внимание, что Adobe PDF Reader должен быть установлен:
1. Выберите ветку и добавьте параметр после открытия файла:
2. Откройте файл PDF:
Добавьте тип gridLayout в макет:
Добавить функцию:
Здесь немного по-другому, вы не можете открыть его напрямую, открыв офис.
Если вам интересно, можете посмотреть официальную документацию. Я ее давно нашел:Портал
3. По окончании эффект открытия выглядит следующим образом:
Работа с офисными файлами и файлами PDF через QAxwidget имеет следующие преимущества и недостатки:
1. Их очень удобно отображать, кода практически нет, вы можете непосредственно увидеть эффект.
2. Суть в том, чтобы вызывать другое программное обеспечение для его отображения. Оно не имеет к этому никакого отношения. Его нельзя экранировать с помощью кнопок. Его нельзя редактировать, копировать или сохранять, поэтому оно прекращается.
3. Если вам нужен исходный код, вы можете оставить комментарий, и я снова его загрузю.
Обновить:
Кодовый адрес:
Портал
In the previous post, I have shown you how to integrate Aspose.Words for C++ in a Qt application using Qt Creator. In this post, we’ll check out how to set up and use Aspose.Words for C++ in Qt using Visual Studio. Later, we will create a Word document within the Qt application.
Set Up Aspose.Words for C++ in Qt Application
For Qt application development in Visual Studio, I have used the following Visual Studio, Qt and Qt VS Tools versions:
Once you have set up the required environment, you can proceed with the following steps for integrating Aspose’ Word library in the Qt application.
- Download and install CMake.
- Download and unpack Aspose.Words for C++.
- Create a new folder for your project files and copy/paste Aspose.Words.Cpp and CodePorting.Native.Cs2Cpp_vc14_20.3 folders from unpacked package.
- Create a new file named CMakeLists.txt in the same folder.
- Copy and paste the following content within the CMakeLists.txt file.
- Open Command Prompt and cd to the project folder.
- Run the following command by replacing with the path to Qt5Config.cmake file (i.e. C:\QT\5.14.2\msvc2017_64\lib\cmake\Qt5).
Once you have completed the above-mentioned steps, a Visual Studio solution will be created in the folder. You are now ready to use Aspose.Words for C++ features within the Qt application. Lets now check out how to create a Word document in this Qt project.
Create Word Documents in Qt Application using Visual Studio
The following are the steps to create a Word document in the Qt application using Aspose.Words for C++:
- Open the solution in Visual Studio.
- Create a new .cpp file named main.cpp and include the following headers files in it.
- Copy/paste the following code in the main function:
- Build and run the application.
Learn more about Aspose.Words for C++
Explore the documentation of Aspose.Words for C++ in order to learn how to create more complex and rich Word documents.
Qt is a popular cross-platform application development framework to develop a variety of applications for desktop, mobile, and embedded systems. C++ based Qt framework uses MOC (Meta-Object Compiler) to generate a standard C++ source from the Qt-extended C++. Since Qt supports a wide range of applications that may target various scenarios, integration of Word automation features (i.e. generating Word documents, Word to PDF, and etc.) within the Qt applications has a big scope.
Aspose.Words for C++ provides nearly all basic and advanced Word automation features and it can positively serve the Word processing requirements within the Qt applications. So let’s see how you can integrate and utilize our C++ Word library to create Word documents within Qt applications.
Integrate Aspose.Words for C++ within Qt Application
In order to integrate Aspose.Words for C++, you are required to download and extract the library files from the downloads section. Once you have, you can proceed with one of the following options to develop Qt applications:
In this blog post, I’ll show you how to integrate and use Aspose.Words for C++ library within a Qt Console Application developed in Qt Creator.
Steps to Add Word Library in Qt Application
I assume that you have properly set up the Qt development environment and installed Qt Creator. Once everything is up and running, you can follow the below steps:
Generate a Word Document in Qt Application
Now you are ready to use Aspose.Words for C++ features. Let’s see how to generate a simple Word document in a Qt application. The following are the steps along with the code snippets required to create a Word document.
- Include the following header files in main.cpp.
- Insert the code to generate a Word DOCX document inside the main function.
- Build and run the application.
Learn more about Aspose.Words for C++
Aspose.Words for C++ also lets you create more complex and rich Word documents. Furthermore, you can perform various document conversions within the Qt applications. Learn more about Aspose.Words for C++ using the documentation.
Share your feedback
In case you would have any questions or queries regarding Aspose.Words for C++, feel free to post on our forum.
Читайте также: