QWidget中含有QComboBox和QSpinBox,将Excel中数据导入到QWidget
看效果
在看代码
void NumView::on_openFileBtn_clicked() { initTabelView(); QString fileName = QFileDialog::getOpenFileName(this, tr("Excel file"), "", "Excel Files(*.xls)"); QAxObject *excel = NULL; //excel设定为Excel文件的操作对象 QAxObject *workbooks = NULL; QAxObject *workbook = NULL; //Excel操作对象 excel = new QAxObject("Excel.Application"); excel->dynamicCall("SetVisible(bool)", false); //true表示操作文件时可见 workbooks = excel->querySubObject("workBooks"); //按文件路径打开文件 workbook = workbooks->querySubObject("Open(QString&)", fileName); QAxObject *worksheets = workbook->querySubObject("WorkSheets");//获取打开的excel文件中所有的工作sheet QAxObject *worksheet = worksheets->querySubObject("Item(int)", 1);//获取第一个工作表querySubObject("Item(int)", n) QAxObject *usedrange = worksheet->querySubObject("UsedRange");//获取该sheet的数据范围(可以理解为有数据的矩形区域) QAxObject *rows = usedrange->querySubObject("Rows");//获取行数 int iRows = rows->property("Count").toInt(); QAxObject *columns = usedrange->querySubObject("Columns");//获取列 int iColumns = columns->property("Count").toInt(); QAxObject *range; int defindex; QString strRow; int icount; //数据处理 for (int i = 0; i < iRows-1; i++) { for (int j = 1; j <= 6; j++) {//iColumns // QChar cCol = (QChar)(j+64); // QString str = cCol; // str = str + QString::number(i) + ":" + str + QString::number(i); // qDebug() << str; // range = worksheet->querySubObject("Range(QString)", str); // qDebug() << range; // QString strRow = ""; // strRow = range->property("Value").toString(); // qDebug() << strRow; //注释的是错误代码 range = worksheet->querySubObject("Cells(int, int)", i+2, j);//i+2, j -这两个参数对应Excel里的第一个要导入的值 strRow = range->dynamicCall("Value2()").toString(); icount = strRow.count()-1; strRow = strRow.mid(0,icount);//这两行是将Excel里获取的字符串中的"\t"去掉 if(j == 2){ defindex = m_stepComboBox[i]->findText(strRow);//索引ComboBox中字符串的序号 m_stepComboBox[i]->setCurrentIndex(defindex);//设置ComboBox }else if(j == 3){ defindex = m_limitComboBox[i]->findText(strRow); m_limitComboBox[i]->setCurrentIndex(defindex); }else if(j == 4){ m_volgate[i]->setValue(strRow.toDouble()); }else if(j == 5){ m_current[i]->setValue(strRow.toDouble()); }else if(j == 6){ m_timeItem[i]->setValue(strRow.toInt()); } } } workbook->dynamicCall("Save()"); workbook->dynamicCall("Close()"); excel->dynamicCall("Quit()"); if(excel) { delete excel; excel = NULL; } }参考了一些大佬的代码,在这里感谢