Qt之操作Excel(QtXlsxWriter)

首先需要安裝qtxlslwriter 這個庫,下載地址:

https://github.com/leolin0518/QtXlsxWriter


打開qt的命令行工具,進入相應的.pro目錄,執行一下命令進行安裝:

1.qmake(生成makefile文件)

2.mingw32-make(編譯源碼)

3.mingw32-make install(編譯安裝)

至此,若不出錯,則順利安裝成功!


文檔:http://qtxlsx.debao.me/


參考文檔:

Qt操作Excel文件 QtXlsxWriter的配置使用說明

Qt下Excel報表生成的又一利器----QtXlsxWriter

http://www.cnblogs.com/lvdongjie/p/4402294.html

C++讀寫EXCEL文件方式比較

在Qt中用QAxObject來操作Excel


問題解決方法:(下載並安裝activeperl)



一個簡單例子

頭文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTableWidget>
#include <QPushButton>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();

    void init();

private slots:
    void slot_writeToExcel();

private:
    QTableWidget *tableWidget;
    QPushButton *btn;
};

#endif // MAINWINDOW_H

源文件

#include "mainwindow.h"

#include <QTableWidgetItem>
#include <QHeaderView>
#include <QDebug>
#include <QtXlsx>
#include <QVBoxLayout>
#include <QWidget>
#include "xlsxabstractsheet.h"

QTXLSX_USE_NAMESPACE        //該命名空間不可少

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    init();
}

MainWindow::~MainWindow()
{

}

void MainWindow::init()
{
    //初始化控件和佈局
    QWidget *widget = new QWidget(this);
    QHBoxLayout *hLayout = new QHBoxLayout;
    QVBoxLayout *vLayout = new QVBoxLayout;

    tableWidget = new QTableWidget(8, 10, widget);
    btn = new QPushButton(tr("生成Excel"), widget);
    connect(btn, SIGNAL(clicked()), this, SLOT(slot_writeToExcel()));

//    hLayout->addSpacing(500);
    hLayout->addStretch(10);
    hLayout->addWidget(btn);

    vLayout->addWidget(tableWidget);
    vLayout->addLayout(hLayout);

    widget->setLayout(vLayout);

    setCentralWidget(widget);
    resize(500, 300);

    int rows = tableWidget->rowCount();         //行數
    int cols = tableWidget->columnCount();      //列數
    for(int i = 0; i < rows; i++){
        for(int j = 0; j < cols; j++){
            QTableWidgetItem *item = new QTableWidgetItem(tr("%1").arg(i+j));
            item->setTextAlignment(Qt::AlignCenter);
            tableWidget->setItem(i, j, item);
        }
    }

    tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    tableWidget->setEditTriggers(QHeaderView::NoEditTriggers);      //不可編輯
    tableWidget->setSelectionBehavior(QHeaderView::SelectRows);     //整行選中
    tableWidget->horizontalHeader()->setVisible(false);             //隱藏列表頭
    tableWidget->verticalHeader()->setVisible(false);               //隱藏行表頭
}

void MainWindow::slot_writeToExcel()
{
    QXlsx::Document xlsx;

    int rows = tableWidget->rowCount();         //行數
    int cols = tableWidget->columnCount();      //列數

    QString text;
    for(int i = 0; i < rows; i++){
        for(int j = 0; j < cols; j++){
            text = tableWidget->item(i, j)->text();
            xlsx.write(i + 1, j + 1, text);
        }
    }

    QXlsx::Format format;                       //格式
    format.setFont(QFont(tr("華文新魏")));       //字體
    format.setFontBold(true);                   //加粗
    format.setFontItalic(true);                 //傾斜
    format.setFontUnderline(Format::FontUnderlineSingle);   //下劃線
    format.setFontColor(Qt::red);               //字體顏色
    format.setHorizontalAlignment(Format::AlignRight);  //對齊方式

    xlsx.setRowFormat(3, 5, format);
    xlsx.setRowHidden(2, true);             //隱藏第二行

    xlsx.renameSheet(tr("Sheet1"), tr("工作計劃"));     //重命名當前Sheet

    xlsx.copySheet("工作計劃", "CopyOfTheFirst");       //無格式拷貝

    xlsx.selectSheet("CopyOfTheFirst");                 //設爲當前顯示Sheet
    xlsx.write(25, 2, "On the Copy Sheet");             //寫
    qDebug() << "111:" << xlsx.read(25, 2).toString();  //讀
    qDebug() << "222:" << xlsx.read("B25").toString();  //讀

    xlsx.copySheet("CopyOfTheFirst", "work1");          //無格式拷貝
    xlsx.moveSheet("work1", 0);                         //移動Sheet在Excel中的位置

    xlsx.sheet("work1")->setVisible(true);              //顯示指定Sheet
//    xlsx.sheet("CopyOfTheFirst")->setVisible(false);    //隱藏指定Sheet

//    xlsx.deleteSheet("CopyOfTheFirst");                //刪除指定Sheet

    xlsx.addSheet(tr("work2"));                         //添加一個Sheet
//    xlsx.sheet("work2")->setSheetState(AbstractSheet::SS_VeryHidden);   //設置指定Sheet狀態爲隱藏

    QString curSheetName = xlsx.currentSheet()->sheetName();
    qDebug() << "curSheetName" << curSheetName;
    xlsx.currentWorksheet()->setGridLinesVisible(false);    //不顯示網格

    xlsx.mergeCells("B1:B3");                           //合併單元格B1:B3

    //設置屬性
    xlsx.write("A1", "View the properties through:");
    xlsx.write("A2", "Office Button -> Prepare -> Properties option in Excel");

    xlsx.setDocumentProperty("title", "This is an example spreadsheet");
    xlsx.setDocumentProperty("subject", "With document properties");
    xlsx.setDocumentProperty("creator", "Debao Zhang");
    xlsx.setDocumentProperty("company", "HMICN");
    xlsx.setDocumentProperty("category", "Example spreadsheets");
    xlsx.setDocumentProperty("keywords", "Sample, Example, Properties");
    xlsx.setDocumentProperty("description", "Created with Qt Xlsx");

    xlsx.selectSheet("工作計劃");                 //設爲當前顯示Sheet

    //獲取表格的行數、列數
    QXlsx::CellRange range;
    range = xlsx.dimension();
    int rowCount = range.rowCount();
    int colCount = range.columnCount();
    qDebug() << "rowCount:" << rowCount << "colCount:" << colCount << xlsx.currentSheet()->sheetName();

    //輸出表格內容
    for (int i = 1; i <= rowCount; i++){
        for (int j = 1; j <= colCount; j++){
            qDebug() << i << j << xlsx.cellAt(i, j)->value().toString();
        }
    }

    xlsx.saveAs("Test.xlsx");                           //另存爲
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章