|
#include "mainwindow.h"
#include <QAxObject>
#include <QmessageBox>
#include <QDebug>
#include <QFile>
#include <QDir>
#include <QFileDialog>
MainWindow::MainWindow(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
connect(ui.ImportPushButton, SIGNAL(clicked()), this,
SLOT(ImportExcel()));
connect(ui.ExportPushButton, SIGNAL(clicked()), this,
SLOT(ExportExcel()));
}
MainWindow::~MainWindow()
{
//excel ,workbooks ,workbook ,worksheets ;excel ,workbook ,workbooks ,worksheet ,usedrange ,rows ,cloumns ,cell
}
void MainWindow::ImportExcel(){
QString FileName = QFileDialog::getOpenFileName(this, tr("Import XLS file"),
tr("."), tr("XLSX File(*.xlsx)"));
if(!FileName.isEmpty()){
QFile file(FileName);
if(!file.open(QIODevice::ReadOnly|QIODevice::Text)){
QMessageBox::warning(this,tr("Read File"),tr("Cannot Import file:\n%1").arg(FileName));
return;
}
QAxObject excel("Excel.Application");
excel.setProperty("Visible",false);
QAxObject *workbooks=excel.querySubObject("WorkBooks");
workbooks->dynamicCall("Add(void)");
QAxObject *workbook=excel.querySubObject("ActiveWorkBook");
QAxObject * worksheet = workbook->querySubObject("WorkSheets(int)", 1);
// workbooks->dynamicCall("Open(const QString&)",FileName);
QAxObject * usedrange = worksheet->querySubObject("UsedRange");//获取该sheet的使用范围对象
QAxObject * rows = usedrange->querySubObject("Rows");
QAxObject * columns = usedrange->querySubObject("Columns");
int intRowStart = usedrange->property("Row").toInt();
int intColStart = usedrange->property("Column").toInt();
int intCols = columns->property("Count").toInt();
int intRows = rows->property("Count").toInt();
QString str;
ui.tableWidget->setRowCount(intRows);
ui.tableWidget->setColumnCount(intCols);
for(int i=intRowStart;i <intRowStart + intRows;i++){
for(int j=intColStart;j <intColStart + intCols;j++){
QAxObject * cell = worksheet->querySubObject("Cells(int,int)", i,j ); //获取单元格
str = cell->property("Value").toString();
if(cell->property("Value").type()==QVariant:ouble){
qDebug()<<QString::number(cell->property("Value").toDouble(),'f',0);
}
else if(cell->property("Value").type()==QVariant::String){
qDebug()<<str;
}
QTableWidgetItem *item = new QTableWidgetItem(str);
ui.tableWidget->setItem(i - intRowStart, j - intColStart, item);
}
}
workbook->dynamicCall("Close (Boolean)", false);
excel.dynamicCall("Quit (void)");
}
}
void MainWindow::ExportExcel(){
}
|
|