Ruslan Polupan
Aug. 9, 2019, 7:16 p.m.

IMpos project. Part 011. Viewing the names of fuel. Export results to xlsx file.

View fuel names.

After processing requests for names, we form a table to display information to the user.


Indication of the process of executing queries to the petrol station databases will be used not only for viewing, but also when exporting to xlsx and when executing scripts that change names. To do this, add one more parameter to the constructor of the ViewFuelNameDialog dialog class that determines further actions. Let's define the list of actions as an enumeration.
tasklist.h

  1. #ifndef TASKLIST_H
  2. #define TASKLIST_H
  3.  
  4. enum taskList { //Список задач
  5. VIEW_NAME, //Просмотр наименований
  6. XLSX_EXPORT, //Экспорт в xlsx
  7. UPDATE_FUEL_NAME //Изменение наименований
  8. };
  9.  
  10. #endif // TASKLIST_H

Let's change the signal handler accepted() buttonBoxView:

  1. void FuelNameDialog::on_buttonBoxView_accepted()
  2. {
  3. //Определяем дальнейший алгоритм работы в зависимости от выбранного checkBox
  4. int currentTask = (ui->radioButtonReport->isChecked()) ? VIEW_NAME : XLSX_EXPORT;
  5. //Диалог для отображения результатов и прогресса получения данных с АЗС
  6. ViewFuelNameDialog *viewFnDlg = new ViewFuelNameDialog(&listTerminals,currentTask, this);
  7. viewFnDlg->exec();
  8. }

In the slotGetStatusThread slot, we add a check for the completion of operations for obtaining names and, depending on the type of task, we call the appropriate function.

  1. ui->progressBarGetFuel->setFormat("Обработано %v из %m. Ошибок "+QString::number(colError));
  2. //Проверяем что произошло получение информации от всех АЗС указанных в списке
  3. //И в зависимости от типа задачи запускаем соответствующую функцию
  4. //Сортируем список азс определив статическую функцию compare
  5. std::sort(m_listFuelName.begin(), m_listFuelName.end(),compare);
  6. if(ui->progressBarGetFuel->value() == m_connectionsList.size()){
  7. switch (m_currentTask) {
  8. case VIEW_NAME:
  9. showFuelName();
  10. break;
  11. case XLSX_EXPORT:
  12. exportXlsx();
  13. break;
  14. default:
  15. break;
  16. }
  17. }

Name mapping implementation function

  1. //Отображение наименований
  2. void ViewFuelNameDialog::showFuelName()
  3. {
  4. QSqlQuery q;
  5. ui->groupBoxProgress->hide();
  6. ui->tableWidgetView->setColumnCount(4);
  7. ui->tableWidgetView->setHorizontalHeaderLabels(QStringList() <<"Резервуар"<<"Код"<<"Краткое"<<"Полное");
  8. ui->tableWidgetView->verticalHeader()->hide();
  9. int colAzs = m_listFuelName.size();
  10. for(int i = 0; i<colAzs; ++i ){
  11. //Добавляем строку с номером и адресом АЗС
  12. int row = ui->tableWidgetView->rowCount();
  13. ui->tableWidgetView->insertRow(row);
  14. QTableWidgetItem *itemAZS = new QTableWidgetItem(QString::number(m_listFuelName.at(i).terminalID())+" "+m_listFuelName.at(i).azsName());
  15. itemAZS->setTextAlignment(Qt::AlignHCenter);
  16. itemAZS->setBackground(QColor("#aaff7f"));
  17. //Объединяем ячейки
  18. ui->tableWidgetView->setSpan(row,0,1,4);
  19. ui->tableWidgetView->setItem(row,0,itemAZS);
  20. for(int j = 0; j<m_listFuelName.at(i).listFuels().size();++j){
  21. //Заполняем строки наименованиями
  22. int rowName = ui->tableWidgetView->rowCount();
  23. ui->tableWidgetView->insertRow(rowName);
  24. ui->tableWidgetView->setItem(rowName,0, new QTableWidgetItem(QString::number(m_listFuelName.at(i).listFuels().at(j).tankID())));
  25. ui->tableWidgetView->item(rowName,0)->setTextAlignment(Qt::AlignCenter);
  26. ui->tableWidgetView->setItem(rowName,1, new QTableWidgetItem(QString::number(m_listFuelName.at(i).listFuels().at(j).fuelID())));
  27. ui->tableWidgetView->item(rowName,1)->setTextAlignment(Qt::AlignCenter);
  28. ui->tableWidgetView->setItem(rowName,2, new QTableWidgetItem(m_listFuelName.at(i).listFuels().at(j).shortName()));
  29. ui->tableWidgetView->setItem(rowName,3, new QTableWidgetItem(m_listFuelName.at(i).listFuels().at(j).name()));
  30. ui->tableWidgetView->resizeColumnToContents(3);
  31. }
  32. }
  33. ui->tableWidgetView->verticalHeader()->setDefaultSectionSize(ui->tableWidgetView->verticalHeader()->minimumSectionSize());
  34. ui->groupBoxView->show();
  35. }

Export results to XSLX file.

To export the results to an xlsx file, we will use the QXlsx library https://qtexcel.github.io/QXlsx/ . I settled on it after looking at examples of use and available instructions for connecting to the project. I compiled the examples and quickly figured out the simplest use of the library.
Connection instructions are available here https://qtexcel.github.io/QXlsx/HowToSetProject.html .

Briefly, it looks like this:
Clone sources from github

  1. git clone https://github.com/j2doll/QXlsx.git

Copy the contents of the QXlsx folder (header, source folder and QXlsx.pri, QXlsx.pro files) to our project folder.

Add to our project file (*.pro)

  1. # QXlsx code for Application Qt project
  2. QXLSX_PARENTPATH=./ # current QXlsx path is . (. means curret directory)
  3. QXLSX_HEADERPATH=./header/ # current QXlsx header path is ./header/
  4. QXLSX_SOURCEPATH=./source/ # current QXlsx source path is ./source/
  5. include(./QXlsx.pri)
  6.  

In the file in which we will use the library, add header files.

  1. #include "xlsxdocument.h"
  2. #include "xlsxchartsheet.h"
  3. #include "xlsxcellrange.h"
  4. #include "xlsxchart.h"
  5. #include "xlsxrichstring.h"
  6. #include "xlsxworkbook.h"
  7. using namespace QXlsx;

The library is ready to use.

  1. void ViewFuelNameDialog::exportXlsx()
  2. {
  3. Document xlsx; // Будущий документ
  4. Format format; // Формат обычных ячеек
  5. Format formatMerge; // Формат объединенной ячейки
  6. Format formatTitle; // Формат заголовка
  7.  
  8. //Задаем параметры форматирования
  9. format.setHorizontalAlignment(Format::AlignHCenter);
  10. format.setVerticalAlignment(Format::AlignVCenter);
  11. format.setBorderStyle(Format::BorderThin);
  12.  
  13. formatMerge.setPatternBackgroundColor(QColor("#aaff7f"));
  14. formatMerge.setHorizontalAlignment(Format::AlignHCenter);
  15. formatMerge.setVerticalAlignment(Format::AlignVCenter);
  16. formatMerge.setBorderStyle(Format::BorderThin);
  17.  
  18. formatTitle.setHorizontalAlignment(Format::AlignHCenter);
  19. formatTitle.setVerticalAlignment(Format::AlignVCenter);
  20. formatTitle.setFontBold(true);
  21. formatTitle.setBorderStyle(Format::BorderThin);
  22. formatTitle.setPatternBackgroundColor(QColor("#A9BCF5"));
  23.  
  24. //Необходимо отметить что нумерация строк и столбцов в xlsx документе начинается с 1
  25. //Устанавливаем ширину столбцов
  26. xlsx.setColumnWidth(1,10);
  27. xlsx.setColumnWidth(4,30);
  28.  
  29. int columnCount = headers.size();
  30. int colAzs = m_listFuelName.size();
  31. //Заполняем заголовки
  32. for(int i =0; i<columnCount; ++i){
  33. xlsx.write(1,i+1, headers.at(i),formatTitle);
  34. }
  35.  
  36. //Табличная часть
  37. int rowX=2;
  38. for(int i=0; i<colAzs; ++i){
  39. xlsx.write(rowX,1, QString::number(m_listFuelName.at(i).terminalID())+" "+m_listFuelName.at(i).azsName());
  40. CellRange cellRange = CellRange(rowX,1,rowX,columnCount);
  41. xlsx.mergeCells(cellRange, formatMerge);
  42. for(int j = 0; j<m_listFuelName.at(i).listFuels().size(); ++j) {
  43. rowX++;
  44. xlsx.write(rowX,1,m_listFuelName.at(i).listFuels().at(j).tankID(),format);
  45. xlsx.write(rowX,2,m_listFuelName.at(i).listFuels().at(j).fuelID(),format);
  46. xlsx.write(rowX,3,m_listFuelName.at(i).listFuels().at(j).shortName(),format);
  47. xlsx.write(rowX,4,m_listFuelName.at(i).listFuels().at(j).name(),format);
  48. }
  49. }
  50. QFile xlsxFile;
  51. //Создаем абсолютный путь к файлу
  52. xlsxFile.setFileName(QApplication::applicationDirPath()+"/"+"FuelName.xlsx");
  53. xlsx.saveAs(xlsxFile.fileName()); // Сохраняем документ
  54. #ifdef Q_OS_WIN
  55. QDesktopServices::openUrl(QUrl("file:///"+xlsxFile.fileName(), QUrl::TolerantMode));
  56. #else
  57. QDesktopServices::openUrl(QUrl("file://"+xlsxFile.fileName(), QUrl::TolerantMode));
  58. #endif
  59. this->reject();
  60. }

We get the FuelName.xlsx file, which is opened by the program by default.

Project archive

iMposCh011.zip iMposCh011.zip

.

By article asked0question(s)

2

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html