Qt对Excel的导入导出,有备无患
void onImportExcel(QString filePath)
{
QAxObject excel("Excel.Application");
excel.setProperty("Visible", false);
QAxObject *work_books = excel.querySubObject("WorkBooks");
work_books->dynamicCall("Open (const QString&)", filePath);
QAxObject *work_book = excel.querySubObject("ActiveWorkBook");
QAxObject *work_sheets = work_book->querySubObject("Sheets"); //Sheets也可换用WorkSheets
int sheet_count = work_sheets->property("Count").toInt(); //获取工作表数目
if(sheet_count > 0)
{
QAxObject *work_sheet = work_book->querySubObject("Sheets(int)", 1);
QAxObject *used_range = work_sheet->querySubObject("UsedRange");
QAxObject *rows = used_range->querySubObject("Rows");
int row_count = rows->property("Count").toInt(); //获取行数
QString txt = work_sheet->querySubObject("Cells(int,int)", i, 1)->property("Value").toString(); //获取单元格内容
work_book->dynamicCall("Close(Boolean)", false); //关闭文件
excel.dynamicCall("Quit(void)"); //退出
}
}
void onExportExcel(QString filePath)
{
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 = first_sheet->querySubObject("Cells(int,int)", 1, 1);
cell->setProperty("Value", "单元格内容");
// cell->setProperty("RowHeight", 50); //设置单元格行高
// cell->setProperty("ColumnWidth", 30); //设置单元格列宽
// cell->setProperty("HorizontalAlignment", -4108); //左对齐(xlLeft):-4131 居中(xlCenter):-4108 右对齐(xlRight):-4152
// cell->setProperty("VerticalAlignment", -4108); //上对齐(xlTop)-4160 居中(xlCenter):-4108 下对齐(xlBottom):-4107
// cell->setProperty("WrapText", true); //内容过多,自动换行
// //cell->dynamicCall("ClearContents()"); //清空单元格内容
// QAxObject* interior = cell->querySubObject("Interior");
// interior->setProperty("Color", QColor(0, 255, 0)); //设置单元格背景色(绿色)
// QAxObject* border = cell->querySubObject("Borders");
// border->setProperty("Color", QColor(0, 0, 255)); //设置单元格边框色(蓝色)
// QAxObject *font = cell->querySubObject("Font"); //获取单元格字体
// font->setProperty("Name", QStringLiteral("华文彩云")); //设置单元格字体
// font->setProperty("Bold", true); //设置单元格字体加粗
// font->setProperty("Size", 20); //设置单元格字体大小
// font->setProperty("Italic", true); //设置单元格字体斜体
// font->setProperty("Underline", 2); //设置单元格下划线
// font->setProperty("Color", QColor(255, 0, 0)); //设置单元格字体颜色(红色)
work_book->dynamicCall("SaveAs(const QString &)", QDir::toNativeSeparators(filePath)); //转换路径不可少,否则会崩溃
work_book->dynamicCall("Close(Boolean)", false); //关闭文件
excel.dynamicCall("Quit(void)"); //退出
}