void MainWindow::on_pushButton_save_data_clicked()
{
// HRESULT r = OleInitialize(0); 若在线程中导出EXecel 需要初始化内存
if(this->model_data_table->rowCount() == 0) {
return;
}
QDir tmp;
if(!tmp.exists(QCoreApplication::applicationDirPath()+"/data"))
{
if(!tmp.mkdir(QCoreApplication::applicationDirPath()+"/data"))
{
QMessageBox::warning(this,tr("警告"),tr("创建目录data失败"),tr("确认"));
return;
}
}
QString filePath = QString("/data/设备%1").arg(this->ui->comboBox_deviceid->currentText());
filePath = QCoreApplication::applicationDirPath() + filePath;
if(tmp.exists(filePath))
{
}else
{
if(!tmp.mkdir(filePath))
{
QMessageBox::warning(this,tr("错误信息"),tr("创建目录%1失败").arg(filePath),tr("确认"));
return;
}
}
filePath += QString("/第%1页%2.xlsx").arg(this->ui->spinBox->value()).arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh-mm-ss"));
filePath.replace("/", "\\");//路径需要’\’反斜杠
QAxObject *work_book = NULL;
QAxObject excel("Excel.Application");
excel.setProperty("Visible", false);
excel.setProperty("DisplayAlerts", false);//不显示任何警告信息
QAxObject *work_books = excel.querySubObject("WorkBooks");
QFile xlsFile(filePath);
if (xlsFile.exists()) {
work_book = work_books->querySubObject("Open(const QString &)", filePath);
}
else {
work_books->dynamicCall("Add");
work_book = excel.querySubObject("ActiveWorkBook");
}
QAxObject *work_sheets = work_book->querySubObject("Sheets");
QAxObject *first_sheet = work_sheets->querySubObject("Item(int)", 1);
QAxObject *cell = NULL;
for(int col=0; col<this->model_data_table->columnCount(); col++) {
cell = first_sheet->querySubObject("Cells(int,int)", 1, col+1);
cell->setProperty("Value", this->model_data_table->headerData(col,Qt::Horizontal).toString());
cell->setProperty("ColumnWidth", 20);
}
for(int i=0;i<this->model_data_table->rowCount();i++)
{
for(int j=0;j<this->model_data_table->columnCount();j++)
{
cell = first_sheet->querySubObject("Cells(int,int)",i+2,j+1);
// cell->setProperty("Value", "无信息");
cell->setProperty("Value", this->model_data_table->index(i,j).data().toString());
cell->setProperty("ColumnWidth", 20); //设置单元格列宽
}
}
work_book->dynamicCall("SaveAs(const QString &)", QDir::toNativeSeparators(filePath)); //转换路径不可少,否则会崩溃
work_book->dynamicCall("Close(Boolean)", false); //关闭文件
excel.dynamicCall("Quit(void)"); //退出
// OleUninitialize();
}