Qt 报表实现(二)----QtXlsx

987 阅读2分钟

文章目录

Qt报表之QtXlsx

QtXlsx是开源的excel文件读写工具,使用起来也比较简单,而且不依赖window的office软件,可以直接生成excel文件;

使用代码示例

源码引用

在项目文件里(.pro)文件中,直接引用QtXlsx的工程文件:

include(QtXlsxWriter/src/xlsx/qtxlsx.pri)

实例代码

代码里注释比写的比较详细了,这里就不对单个函数单独说明了

void testQtxlsx()
{
    QXlsx::Document xlsx;

    xlsx.setColumnWidth(1,7,12);  //设置列宽

    QXlsx::Format centerAlign;
    centerAlign.setHorizontalAlignment(QXlsx::Format::AlignHCenter); //设置横向、纵向居中
    centerAlign.setVerticalAlignment(QXlsx::Format::AlignVCenter);   //

    centerAlign.setFontBold(true);          //字体加粗
    centerAlign.setFontColor(Qt::blue);     //设置字体颜色
    centerAlign.setFontSize(30);            //设置字体大小
    //设置上下左右的线类型
    centerAlign.setTopBorderStyle(QXlsx::Format::BorderThin);
    centerAlign.setBottomBorderStyle(QXlsx::Format::BorderThin);
    centerAlign.setLeftBorderStyle(QXlsx::Format::BorderThin);
    centerAlign.setRightBorderStyle(QXlsx::Format::BorderThin);

    xlsx.mergeCells(1,1,1,7,centerAlign); //合并单元表格
    xlsx.write("A1", "测试结果报表");       //总标题


    centerAlign.setFontColor(Qt::black);  //设置字体颜色
    centerAlign.setFontSize(13);          //设置字体大小
    xlsx.mergeCells(2,1,1,7,centerAlign); //副标题合并单元表格,2-第二行,1-7列合并
    xlsx.write("A2", "1号实验报表");        //副标题

    xlsx.mergeCells(3,1,1,2,centerAlign);   //合并单元表格
    xlsx.write("A3","测试人:",centerAlign);  //
    xlsx.mergeCells(3,3,1,2,centerAlign);
    xlsx.write("C3","结果: 合格");

    xlsx.mergeCells(3,5,1,3,centerAlign);
    xlsx.write("E3", "检测时间:2020-12-13",centerAlign);

    centerAlign.setFontBold(false);
    centerAlign.setFontSize(10);


    //填充测试数据单元表格
    for (int row = 4; row < 50; row++)
    {
        for (int col = 0; col < 7; col++ )
        {
            xlsx.write(row,col+1, col,centerAlign);
        }
    }
    // save file. 直接保存到程序所在目录
    QString strPath = QGuiApplication::applicationDirPath()+"/"+"test"+".xlsx";
    xlsx.saveAs(strPath);
    
	return;
}

生成表格的效果

在这里插入图片描述
打印预览:
在这里插入图片描述

结束语

如果说数据不是太特殊,使用这个方式还是很简单的。
另外使用这个工具可以实现图标统计图,有时间可以自己研究研究。

微信公众号:
在这里插入图片描述