在AutoCAD中動態(tài)讀取Excel數據
在實際的工作中,我們經常要對一些表格數據進行處理,如果先把這些表格數據通過Excel處理,再導入到AutoCAD,
那絕對會起到事半功倍的效果。隨著Automation編程技術的出現,我們可以很方便地實現這一點了,下面是個
ObjectARX的例子,其功能是動態(tài)關聯Excel,然后讀取其數據,并將這些數據打印在文本域中。
//動態(tài)從Excel讀取數據
int DynamicReadFromExcel()
{
//常用變量定義
_Application app;
Workbooks books;
_Workbook book;
Worksheets sheets;
_Worksheet sheet;
Range range;
Range iCell;
LPDISPATCH lpDisp;
COleVariant
covTrue((short)TRUE),
covFalse((short)FALSE),
covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
COleVariant vResult;
//采用MFC方式初始化COM庫,程序結束時COM庫會自動釋放
if(!AfxOleInit())
{
MessageBox(NULL,"初始化COM支持庫失敗!\n無法控制Excel!", \
"TrueTable",MB_IConERROR | MB_OK);
return RTERROR;
}
//關聯已經運行的Excel實例
CLSID clsid;
CLSIDFromProgID(L"Excel.Application", &clsid);
IUnknown *pUnk = NULL;
IDispatch *pRunDisp = NULL;
for(long i=1;i<=5;i++) //做5次嘗試
{
HRESULT hr = GetActiveObject(clsid, NULL, (IUnknown**)&pUnk);
if(SUCCEEDED(hr))
{
hr = pUnk->QueryInterface(IID_IDispatch, (void **)&pRunDisp);
break;
}
::Sleep(10);
}
if (!pRunDisp)
{
::MessageBox(NULL, "沒有發(fā)現Excel!", "TrueTable", MB_ICONHAND);
return RTERROR;
}
if (pUnk) pUnk->Release();
//關聯Excel
app.AttachDispatch (pRunDisp);
//得到當前活躍sheet
//如果有單元格正處于編輯狀態(tài)中,此操作不能返回,會一直等待
lpDisp=app.GetActiveSheet();
if(lpDisp==NULL)
{
MessageBox(NULL, "沒有發(fā)現有效的表格!", \
"TrueTable",MB_IConERROR | MB_OK);
app.ReleaseDispatch ();
return RTERROR;
}
sheet.AttachDispatch(lpDisp);
//已經使用的行數:
long row_num;
range.AttachDispatch(sheet.GetUsedRange());
range.AttachDispatch(range.GetRows());
row_num=range.GetCount();
//已經使用的列數:
long col_num;
range.AttachDispatch(sheet.GetUsedRange());
range.AttachDispatch(range.GetColumns());
col_num=range.GetCount();
//已經使用區(qū)域的起始行、列:
range.AttachDispatch(sheet.GetUsedRange());
long StartRow=range.GetRow(); //起始行
long StartCol=range.GetColumn(); //起始列
//讀取sheet名
CString SheetName=sheet.GetName();
//ads_printf("\n%s",SheetName);
if(col_num<2 && row_num<2) //此sheet為空
{
MessageBox(NULL,"\n當前表格沒有數據!", \
"TrueTable",MB_IConERROR | MB_OK);
app.ReleaseDispatch ();
return RTERROR;
}
else
{
ads_printf("\n表格%s共%d行,%d列",SheetName,row_num,col_num);
}
//得到全部Cells,此時,range是cells的集合
range.AttachDispatch(sheet.GetCells());
//讀寫數據了
CString cstr;
ads_printf("\n");
for(long i=StartRow;i<StartRow+row_num;i++)
{
for(long j=StartCol;j<StartCol+col_num;j++)
{
//讀取單元格文本
iCell.AttachDispatch(range.GetItem (COleVariant(i),COleVariant(j)).pdispVal );
vResult =iCell.GetText();
cstr=vResult.bstrVal;
//寫單元格文本
ads_printf("%s ",(LPTSTR)cstr);
}
ads_printf("\n");
}
//釋放Dispatch
iCell.ReleaseDispatch ();
range.ReleaseDispatch ();
sheet.ReleaseDispatch ();
sheets.ReleaseDispatch ();
book.ReleaseDispatch ();
books.ReleaseDispatch ();
app.ReleaseDispatch ();
return RTNORM;
}
如果要輸出到Excel的話,關鍵函數就是:
iCell.SetItem(COleVariant(i),COleVariant(j),COleVariant(cstr)); |