资源简介
原博客地址:http://blog.csdn.net/frank3543/article/details/45042977
测试可使用,方便大家,有什么问题的请指出。我是qt5,配置照着项目应该没问题。
代码片段和文件信息
#include “excelengine.h“
ExcelEngine::ExcelEngine()
{
pExcel = NULL;
pWorkbooks = NULL;
pWorkbook = NULL;
pWorksheet = NULL;
sXlsFile = ““;
nRowCount = 0;
nColumnCount = 0;
nStartRow = 0;
nStartColumn = 0;
bIsOpen = false;
bIsValid = false;
bIsANewFile = false;
bIsSaveAlready = false;
HRESULT r = OleInitialize(0);
if (r != S_OK && r != S_FALSE)
{
qDebug(“Qt: Could not initialize OLE (error %x)“ (unsigned int)r);
}
}
ExcelEngine::ExcelEngine(QString xlsFile)
{
pExcel = NULL;
pWorkbooks = NULL;
pWorkbook = NULL;
pWorksheet = NULL;
sXlsFile = xlsFile;
nRowCount = 0;
nColumnCount = 0;
nStartRow = 0;
nStartColumn = 0;
bIsOpen = false;
bIsValid = false;
bIsANewFile = false;
bIsSaveAlready = false;
HRESULT r = OleInitialize(0);
if (r != S_OK && r != S_FALSE)
{
qDebug(“Qt: Could not initialize OLE (error %x)“ (unsigned int)r);
}
}
ExcelEngine::~ExcelEngine()
{
if ( bIsOpen )
{
//析构前,先保存数据,然后关闭workbook
Close();
}
OleUninitialize();
}
/**
*@brief 打开sXlsFile指定的excel报表
*@return true : 打开成功
* false: 打开失败
*/
bool ExcelEngine::Open(UINT nSheet bool visible)
{
if ( bIsOpen )
{
//return bIsOpen;
Close();
}
nCurrSheet = nSheet;
bIsVisible = visible;
if ( NULL == pExcel )
{
pExcel = new QAxobject(“Excel.Application“);
if ( pExcel )
{
bIsValid = true;
}
else
{
bIsValid = false;
bIsOpen = false;
return bIsOpen;
}
pExcel->dynamicCall(“SetVisible(bool)“ bIsVisible);
}
if ( !bIsValid )
{
bIsOpen = false;
return bIsOpen;
}
if ( sXlsFile.isEmpty() )
{
bIsOpen = false;
return bIsOpen;
}
/*如果指向的文件不存在,则需要新建一个*/
QFile f(sXlsFile);
if (!f.exists())
{
bIsANewFile = true;
}
else
{
bIsANewFile = false;
}
if (!bIsANewFile)
{
pWorkbooks = pExcel->querySubobject(“WorkBooks“); //获取工作簿
pWorkbook = pWorkbooks->querySubobject(“Open(QString QVariant)“sXlsFileQVariant(0)); //打开xls对应的工作簿
}
else
{
pWorkbooks = pExcel->querySubobject(“WorkBooks“); //获取工作簿
pWorkbooks->dynamicCall(“Add“); //添加一个新的工作薄
pWorkbook = pExcel->querySubobject(“ActiveWorkBook“); //新建一个xls
}
pWorksheet = pWorkbook->querySubobject(“WorkSheets(int)“ nCurrSheet);//打开sheet
//至此已打开,开始获取相应属性
QAxobject *usedrange = pWorksheet->querySubobject(“UsedRange“);//获取该sheet的使用范围对象
QAxobject *rows = usedrange->querySubobject(“Rows“);
QAxobject *columns = usedrange-
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 10094 2018-01-29 10:51 excelTest\excelengine.cpp
文件 1260 2018-01-29 10:32 excelTest\excelengine.h
文件 1234 2018-01-29 10:16 excelTest\excelTest.pro
文件 23855 2018-01-29 09:35 excelTest\excelTest.pro.user
文件 175 2018-01-26 14:50 excelTest\main.cpp
文件 614 2018-01-29 10:54 excelTest\widget.cpp
文件 414 2018-01-29 10:53 excelTest\widget.h
文件 1256 2018-01-29 10:34 excelTest\widget.ui
目录 0 2018-01-29 10:58 excelTest
----------- --------- ---------- ----- ----
38902 9
评论
共有 条评论