Qt QTableWidget table export as html table

Qt QTableWidget table export as html table

1. Brief introduction

Note--QTableWidget is exported as html table.

Examples of uses:

1. Data comparison, such as database data, needs to be compared and merged. At this time, it can be converted into text, and then use beyong compare, meld and other tools to compare the differences.

2. Common scenarios. Compared with an excel form, the excel form needs to be viewed by office or wps tools. HTML only needs to be viewed by a browser, mobile and PC (windos, linux, IOS are acceptable), and the data is light and portable.

Example packaging: Download: https://wwa.lanzoui.com/iusW5pspozc Password: hd8v

Second, the effect

Three, engineering structure

Four, test code

HtmlTable.pro file

QT       += core gui greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = HtmlTableTEMPLATE = app  SOURCES += main.cpp\        mainwindow.cpp \    htmltable.cpp HEADERS  += mainwindow.h \    htmltable.h FORMS    += mainwindow.ui

htmltable.h file

#ifndef HTMLTABLE_H#define HTMLTABLE_H #include <QList> #define TABEL_TD_TEXT_MAX_LEN   (256) enum {    ALIGN_LEFT      = 1,    ALIGN_RIGHT     = 2,    ALIGN_CENTER    = 3}; enum {    Out_FAIL    = -1,    Out_OK      = 0,}; typedef struct {    unsigned int align;    unsigned int colspan;    unsigned int rowspan;    unsigned int bgColor;    char text[TABEL_TD_TEXT_MAX_LEN];} Table_TD_t; typedef struct {    QList<Table_TD_t> td_list;} Table_TR_t; typedef struct {    QString title;    QString info;    QList<Table_TR_t> tr_list;} Table_t; int OutHtmlTable(QString filePath, Table_t *table); #endif // HTMLTABLE_H

mainwindow.h file

#ifndef MAINWINDOW_H#define MAINWINDOW_H #include <QMainWindow> #define MIN(a,b)    ((a)>(b)?(a):(b))#define TEST_TABLE_ROW_COUNT    (5)#define TEST_TABLE_COL_COUNT    (10)#define DATE_TIME_STR_MAX_LEN   (32) namespace Ui {class MainWindow;} class MainWindow : public QMainWindow{    Q_OBJECT public:    explicit MainWindow(QWidget *parent = 0);    ~MainWindow(); private slots:    void on_pushButtonTestHtmlTable_clicked();     void on_pushButtonExportHtmltable_clicked(); private:    Ui::MainWindow *ui;}; #endif // MAINWINDOW_H

htmltable.cpp file

#include "htmltable.h"#include <QFile>#include <QTextStream> //文本对齐ID转字符串static QString Align2Str(int align){    QString align_str = "";    switch (align)    {        case ALIGN_LEFT:            align_str = "left";            break;        case ALIGN_RIGHT:            align_str = "right";            break;        case ALIGN_CENTER:            align_str = "center";            break;    }    return align_str;} //格式化TD行static QString FormatTD(Table_TD_t &td) {    QString td_str = "<td";     //文本对齐    if (0 < td.align) {        td_str += " align=\"";        td_str += Align2Str(td.align);        td_str += "\"";    }     //跨列    if (0 < td.colspan) {        td_str += QString::asprintf(" colspan=\"%d\"", td.colspan);    }     //跨行    if (0 < td.rowspan) {        td_str += QString::asprintf(" rowspan=\"%d\"", td.rowspan);    }     //背景色 bgcolor    if (0 < td.bgColor) {        td_str += QString::asprintf(" bgcolor=\"#%x\"", td.bgColor);    }     td_str += ">";     //内容    if (strnlen(td.text, sizeof(td.text))) {        td_str += QString::fromLocal8Bit(td.text);    }     td_str += "</td>";    return td_str;} //输出Html表格int OutHtmlTable(QString filePath, Table_t *table){    int i;    int j;    int tr_count;    int td_count;     if (NULL == table) {        return Out_FAIL;    }     QFile file(filePath);    if( file.open(QIODevice::WriteOnly | QIODevice::Text) ) {        QTextStream out(&file);         out << QString("<!DOCTYPE html>") << endl;        out << QString("<html>") << endl;        out << QString("<head>") << endl;        out << QString("<meta charset=\"utf-8\">") << endl;        out << QString("<title>");        out << table->title << QString("</title>") << endl;        out << QString("</head>") << endl;        out << QString("<body>") << endl;        out << QString(table->info) << endl;        out << QString("<table border=\"1\">") << endl;        //数据        tr_count = table->tr_list.count();        for (i = 0; i < tr_count; ++i) {            out << QString("<tr>") << endl;             //td 行数据            td_count = table->tr_list[i].td_list.count();            for (j = 0; j < td_count; ++j) {                out << FormatTD(table->tr_list[i].td_list[j]) << endl;            }             out << QString("</tr>") << endl;        }         out << QString("</table>") << endl;        out << QString("</body>") << endl;        out << QString("</html>") << endl;         file.close();        return Out_OK;    }    return Out_FAIL;}

main.cpp file

#include "mainwindow.h"#include <QApplication>#include <QTextCodec> int main(int argc, char *argv[]){     QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));    QApplication a(argc, argv);    MainWindow w;    w.show();     return a.exec();}

mainwindow.cpp file

#include "mainwindow.h"#include "ui_mainwindow.h"#include "htmltable.h"#include <QMessageBox>#include <QDateTime>#include <QFileDialog> MainWindow::MainWindow(QWidget *parent) :    QMainWindow(parent),    ui(new Ui::MainWindow){    ui->setupUi(this);    this->setWindowTitle(tr("Html表格测试"));    ui->tableWidget->setRowCount(3);    ui->tableWidget->setColumnCount(2);    QStringList strList ;    strList << "努力" << "奋斗";    ui->tableWidget->setHorizontalHeaderLabels(strList);    ui->tableWidget->verticalHeader()->setVisible(false);    ui->tableWidget->setItem(0,0,new QTableWidgetItem("加油"));    ui->tableWidget->setItem(0,1,new QTableWidgetItem("坚持"));    ui->tableWidget->setItem(1,0,new QTableWidgetItem("勤奋"));    ui->tableWidget->setItem(1,1,new QTableWidgetItem("学习"));    ui->tableWidget->setItem(2,0,new QTableWidgetItem("世界"));    ui->tableWidget->setItem(2,1,new QTableWidgetItem("和平"));} MainWindow::~MainWindow(){    delete ui;} void MainWindow::on_pushButtonTestHtmlTable_clicked(){    int i;    int j;    int row_count = TEST_TABLE_ROW_COUNT;    int col_count = TEST_TABLE_COL_COUNT;    Table_t table;    table.title = "Hello Html Table";    table.info = QString("Table Create Time:") + \            QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");     //首行    Table_TD_t table_td_head = {ALIGN_CENTER, 0, 0, 0, ""};    Table_TR_t table_tr_head;     //序号列    strcpy(table_td_head.text, "No.");    table_tr_head.td_list.append(table_td_head);     //合并2列    table_td_head.colspan = 2;    table_td_head.bgColor = 0xcce8cf;    strcpy(table_td_head.text, "标题1");    table_tr_head.td_list.append(table_td_head);     //合并5列    table_td_head.colspan = 5;    table_td_head.bgColor = 0x99CCFF;    strcpy(table_td_head.text, "标题2");    table_tr_head.td_list.append(table_td_head);     //合并2列    table_td_head.colspan = 3;    table_td_head.bgColor = 0x99FF99;    strcpy(table_td_head.text, "标题3");    table_tr_head.td_list.append(table_td_head);    table.tr_list.append(table_tr_head);     //表格内容1    Table_TD_t table_td = {0, 0, 0, 0, ""};    for (i = 0; i < row_count; i++) {        Table_TR_t table_tr;        sprintf(table_td.text, "%d", i+1);        table_tr.td_list.append(table_td);        for (j = 0; j < col_count; j++) {            sprintf(table_td.text, "Hello %d", j);            table_tr.td_list.append(table_td);        }        table.tr_list.append(table_tr);    }     //合并行测试    Table_TD_t table_td2 = {ALIGN_CENTER, 0, 0, 0, ""};    Table_TR_t table_tr2;     table_td2.rowspan = col_count;    strcpy(table_td2.text, "合并行测试");    table_tr2.td_list.append(table_td2);    table.tr_list.append(table_tr2);     //表格内容2    Table_TD_t table_td3 = {0, 0, 0, 0, ""};    for (i = 0; i < row_count; i++) {        Table_TR_t table_tr;        sprintf(table_td3.text, "%d", i+1);        table_tr.td_list.append(table_td3);        for (j = 0; j < col_count - 1; j++) {            sprintf(table_td3.text, "Hello %d", j);            table_tr.td_list.append(table_td3);        }        table.tr_list.append(table_tr);    }     //打开文件对话框,返回选择文件的绝对路径  父窗体   标题      默认打开路径(不写就会打开当前路径)    QString save_file = QFileDialog::getSaveFileName(this, \                                                     tr("保存文件"), \                                                     "C:\\Users\\Liang\\Desktop\\test1.html", \                                                     tr("html文件(*.html)"));    if (0 >= save_file.length()) {        return;    }     if (Out_OK == OutHtmlTable(save_file, &table)) {        QMessageBox::information(this, tr("提示"), tr("已输出到")+save_file);    } else {        QMessageBox::critical(this, tr("提示"), tr("导出html失败!"));    }} void MainWindow::on_pushButtonExportHtmltable_clicked(){    int row;    int col;    int row_count = ui->tableWidget->rowCount();    int col_count = ui->tableWidget->columnCount();    QString str = "";     //打开文件对话框,返回选择文件的绝对路径  父窗体   标题      默认打开路径(不写就会打开当前路径)    QString save_file = QFileDialog::getSaveFileName(this, \                                                     tr("保存文件"), \                                                     "C:\\Users\\Liang\\Desktop\\test1.html", \                                                     tr("html文件(*.html)"));    if (0 >= save_file.length()) {        return;    }     Table_t table;    table.title = "Hello Html Table";    table.info = QString("Table Create Time:") + \            QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");     //首行    Table_TD_t table_td_head = {ALIGN_CENTER, 0, 0, 0, ""};    Table_TR_t table_tr_head;    for (col = 0; col < col_count; col++) {        str = ui->tableWidget->horizontalHeaderItem(col)->text();        strncpy(table_td_head.text, \                str.toLocal8Bit().data(),                sizeof(table_td_head.text)-1);        table_tr_head.td_list.append(table_td_head);    }    table.tr_list.append(table_tr_head);     //表格内容    Table_TD_t table_td = {0, 0, 0, 0, ""};    for (row = 0; row < row_count; row++) {        Table_TR_t table_tr;        for(col = 0; col < col_count; col++) {            str = ui->tableWidget->item(row, col)->text();            strncpy(table_td.text, \                    str.toLocal8Bit().data(),                    sizeof(table_td.text)-1);            table_tr.td_list.append(table_td);        }        table.tr_list.append(table_tr);    }      if (Out_OK == OutHtmlTable(save_file, &table)) {        QMessageBox::information(this, tr("提示"), tr("已输出到")+save_file);    } else {        QMessageBox::critical(this, tr("提示"), tr("导出html失败!"));    }}

Five, to be improved