Qt Xlsx安装教程
安装perl
如果没有安装perl,请参考perl Window安装教程
下载QtXlsxWriter源码
ming32-make编译32 lib库
bash
C:\Qt\Qt5.12.12\5.12.12\mingw73_32>d:
D:\>cd D:\Code\QtXlsxWriter-master\QtXlsxWriter-master
D:\Code\QtXlsxWriter-master\QtXlsxWriter-master>cd src
D:\Code\QtXlsxWriter-master\QtXlsxWriter-master\src 的目录
D:\Code\QtXlsxWriter-master\QtXlsxWriter-master\src>qmake src.pro
D:\Code\QtXlsxWriter-master\QtXlsxWriter-master\src>mingw32-make
D:\Code\QtXlsxWriter-master\QtXlsxWriter-master\src>mingw32-make install
ming32-make编译64 lib库
bash
C:\Qt\Qt5.12.12\5.12.12\mingw73_64>d:
D:\>cd D:\Code\QtXlsxWriter-master\QtXlsxWriter-master
D:\Code\QtXlsxWriter-master\QtXlsxWriter-master>cd src
D:\Code\QtXlsxWriter-master\QtXlsxWriter-master\src 的目录
D:\Code\QtXlsxWriter-master\QtXlsxWriter-master\src>qmake src.pro
D:\Code\QtXlsxWriter-master\QtXlsxWriter-master\src>mingw32-make
D:\Code\QtXlsxWriter-master\QtXlsxWriter-master\src>mingw32-make install
测试读写接口
CMakeLists.txt
bash
cmake_minimum_required(VERSION 3.14)
project(TestQtXlsx LANGUAGES CXX)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(QT NAMES Qt6 Qt5 COMPONENTS Core Xlsx REQUIRED)
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core Xlsx REQUIRED)
add_executable(TestQtXlsx
main.cpp
)
target_link_libraries(TestQtXlsx Qt${QT_VERSION_MAJOR}::Core)
target_link_libraries(TestQtXlsx Qt${QT_VERSION_MAJOR}::Xlsx)
测试代码
cpp
#include <QCoreApplication>
#include <QDate>
#include <QTime>
#include <QDebug>
#include "xlsxdocument.h"
static void test_xlsx_write()
{
//定义一个QXlsx文档对象
QXlsx::Document xlsx("example.xlsx");
//设置单元格水平左对齐 垂直居中对齐格式
QXlsx::Format format;
format.setHorizontalAlignment(QXlsx::Format::AlignLeft);
format.setVerticalAlignment(QXlsx::Format::AlignVCenter);
//写第1列第1行单元格内容
xlsx.write("A1", "Hello Qt!", format);
//写第1列第2行单元格内容
xlsx.write("A2", 12345,format);
//写第1列第3行单元格内容
xlsx.write("A3", "=44+33",format);
//写第1列第4行单元格内容
xlsx.write("A4", true,format);
//写第1列第5行单元格内容
xlsx.write("A5", "http://qt-project.org",format);
//写第1列第6行单元格内容
xlsx.write("A6", QDate(2013, 12, 27),format);
//写第1列第7行单元格内容
xlsx.write("A7", QTime(6, 30),format);
//设置行高和列宽
QXlsx::CellRange range = xlsx.dimension();
int row = range.rowCount();
int col = range.columnCount();
xlsx.setColumnWidth(1,col,30);
xlsx.setRowHeight(1,row, 20);
//保存xlsx文件
xlsx.save();
return ;
}
static void test_xlsx_read()
{
//定义一个QXlsx文档对象
QXlsx::Document xlsx("example.xlsx");
//读取行列数
QXlsx::CellRange range = xlsx.dimension();
int row = range.rowCount();
int col = range.columnCount();
qDebug()<<"row="<<row<<"col="<<col;
//读取第1列第2行内容
int a2 = xlsx.read("A2").toInt();
qDebug()<<"A2 content="<<a2;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
test_xlsx_write();
test_xlsx_read();
return a.exec();
}
测试结果
参考文献:
Qt Xlsx使用教程、Qt操作Excel、Qt生成Excel图表、跨平台不依赖Office
Qt之qtxlsx(Excel读取)开源库使用示例
QtXlsxWriter源码地址