#include "ExcelExport.h" #include #include #include #include using namespace std; ExcelExport::ExcelExport() {} void ExcelExport::newExcel(const QString &fileName) { HRESULT r = OleInitialize(0); if (r != S_OK && r != S_FALSE) { qDebug() << "初始化失败"; } pApplication = new QAxObject(); //连接Excel控件 pApplication->setControl("Excel.Application"); // false不显示窗体(看具体过程) pApplication->dynamicCall("SetVisible(bool)", false); //不显示任何警告信息 pApplication->setProperty("DisplayAlerts", false); pWorkBooks = pApplication->querySubObject("Workbooks"); QFile file(fileName); if (file.exists()) { file.remove(); // pWorkBook = pWorkBooks->querySubObject("Open(const QString &", fileName); } // else { pWorkBooks->dynamicCall("Add"); pWorkBook = pApplication->querySubObject("ActiveWorkBook"); //} //默认有一个worksheet pSheets = pWorkBook->querySubObject("Sheets"); pSheet = pSheets->querySubObject("Item(int)", 1); } void ExcelExport::appendSheet(const QString &sheetName) { int cnt = pSheets->property("Count").toInt(); qDebug() << "appent---" << cnt; QAxObject *pLastSheet = pSheets->querySubObject("Item(int)", cnt); pSheets->querySubObject("Add(QVariant)", pLastSheet->asVariant()); pSheet = pSheets->querySubObject("Item(int)", cnt); pLastSheet->dynamicCall("Move(QVariant)", pSheet->asVariant()); pSheet->setProperty("Name", sheetName); } void ExcelExport::setCellValue(int row, int column, const QString &value) { QAxObject *pRange = pSheet->querySubObject("Cells(int,int)", row, column); pRange->setProperty("NumberFormatLocal", "@"); pRange->dynamicCall("Value", value); //内容居中 pRange->setProperty("HorizontalAlignment", -4108); pRange->setProperty("VerticalAlignment", -4108); } void ExcelExport::setHeaderCellValue(int row, int column, const QString &value) { QAxObject *pRange = pSheet->querySubObject("Cells(int,int)", row, column); QAxObject *cells = pRange->querySubObject("Columns"); cells->dynamicCall("AutoFit"); pRange->setProperty("NumberFormatLocal", "@"); //换行 pRange->setProperty("WrapText", true); //宽度 pRange->setProperty("ColumnWidth", value.length() == 0 ? 20 : value.length() * 3); pRange->dynamicCall("Value", value); //内容居中 pRange->setProperty("HorizontalAlignment", -4108); pRange->setProperty("VerticalAlignment", -4108); } void ExcelExport::setCellValue(int row, int column, const int &value) { QAxObject *pRange = pSheet->querySubObject("Cells(int,int)", row, column); pRange->setProperty("Value", value); //内容居中 pRange->setProperty("HorizontalAlignment", -4108); pRange->setProperty("VerticalAlignment", -4108); } void ExcelExport::saveExcel(const QString &fileName) { //删除第一个sheet页 QAxObject *firstSheet = pSheets->querySubObject("Item(int)", 1); firstSheet->dynamicCall("delete"); //保存 pWorkBook->dynamicCall("SaveAs(const QString &)", QDir::toNativeSeparators(fileName)); if (pApplication != NULL) { qDebug() << "退出"; pApplication->dynamicCall("Quit(void)"); //退出 delete pApplication; pApplication = NULL; } } ExcelExport::~ExcelExport() {}