一、CSV文件

CSV 是纯文本格式,用逗号分隔每一列,换行表示每一行,适合导出表格型数据。

QVector<ExperimentData> dataList;

/** 获取数据库数据步骤省略... **/

QFile file(filePath);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    return;
file.write("\xEF\xBB\xBF"); // UTF-8 BOM

QTextStream out(&file);
out << "序号,运行阶段,运行时间,搁板温度,真空度\n";
for (int i = 0; i < dataList.size(); ++i)
{
    const auto &data = dataList[i];
    out << QString("%1,%2,%3,%4,%5\n")
            .arg(i + 1)
            .arg(ExperimentData::stageToString(data.stage))
            .arg(ExperimentData::formatSeconds(data.runtime))
            .arg(data.clapboardTemp)
            .arg(data.vacuum);
}

二、EXCEL文件

需要引入第三方库 QXlsx,生成原生 .xlsx,跨平台。

Document xlsx;
xlsx.write("A1", "序号");
xlsx.write("B1", "运行阶段");
xlsx.write("C1", "运行时间");
xlsx.write("D1", "搁板温度");
xlsx.write("E1", "真空度");

int row = 2;
int index = 1;
while (query.next())
{
    xlsx.write(row, 1, index++);
    xlsx.write(row, 2, ExperimentData::stageToString(query.value("stage").toInt()));
    xlsx.write(row, 3, ExperimentData::formatSeconds(query.value("runtime").toInt()));
    xlsx.write(row, 4, query.value("clapboard_temp").toDouble());
    xlsx.write(row, 5, query.value("vacuum").toDouble());
    ++row;
}

if (!xlsx.saveAs(filePath))
    return;

三、PDF文件

通过 QPainter 把界面或图表绘制内容绘制到 QImage / QPdfWriter 等设备上,实现“截图”导出。

    // Create HTML table
QString html = "<h2 align='center'>实验数据报告</h2>";
html += "<table border='1' cellspacing='0' cellpadding='4' width='100%'>";
html += "<tr><th>序号</th><th>运行阶段</th><th>运行时间</th><th>搁板温度</th><th>真空度</th></tr>";

int index = 1;
while (query.next())
{
    html += QString("<tr><td>%1</td><td>%2</td><td>%3</td><td>%4</td><td>%5</td></tr>")
                .arg(index++)
                .arg(ExperimentData::stageToString(query.value("stage").toInt()))
                .arg(ExperimentData::formatSeconds(query.value("runtime").toInt()))
                .arg(query.value("clapboard_temp").toDouble())
                .arg(query.value("vacuum").toDouble());
}

html += "</table>";

// Output to PDF
QPrinter printer(QPrinter::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(filePath);

QTextDocument doc;
doc.setHtml(html);
doc.print(&printer);

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐