QXlsx基本操作记录
程序员文章站
2024-01-30 16:31:04
...
-
打开一个Excel文件
QString filePath = QFileDialog::getSaveFileName(this, tr("选择保存路径"), tr("新建.xlsx").arg(modelName), QStringLiteral("*.xlsx"));
if(filePath.isEmpty())
{
return;
}
QXlsx::Document xlsxDocument(filePath);
-
单元格样式设置
QXlsx::Format titleFormat;//标题单元格样式
titleFormat.setFontSize(20);/*设置字体大小*/
titleFormat.setFontBold(true);//字体加粗
titleFormat.setHorizontalAlignment(QXlsx::Format::AlignHCenter);//横向居中
titleFormat.setVerticalAlignment(QXlsx::Format::AlignVCenter);//纵向居中
titleFormat.setBorderStyle(QXlsx::Format::BorderDashDotDot);//边框样式
-
写入单元格
xlsxDocument.write(1, 1, QString("测试"),titleFormat);
-
合并单元格,将(3,1)至(3,3)合并为一个单元格
xlsxDocument.mergeCells(QXlsx::CellRange(3,1,3,3), tableTitleFormat);
-
保存Excel文件
xlsxDocument.saveAs(filePath);
-
获取行列数
QXlsx::Document xlsx(filePath);
QXlsx::Workbook *workBook = xlsx.workbook();
QXlsx::Worksheet *workSheet = static_cast<QXlsx::Worksheet*>(workBook->sheet(0));
int row = workSheet->dimension().rowCount();
int col = workSheet->dimension().columnCount();
-
遍历内容
for(int i = 1;i <= row;++i)
{
for(int j = 1;i <= col;++j)
{
if(QXlsx::Cell * cell = workSheet->cellAt(i, j))
{
qDebug()<< cell->value().toString();
}
}
}