MFC將ListControl中的資料匯出到Excel
匯出Excel的第一種方法用的是:
Excel::_ApplicationPtr ptrExcelApp;
Excel::_WorkbookPtr ptrBook;
Excel::_WorksheetPtr ptrSheet;
Excel::RangePtr ptrRange;
#import "C:\\Program Files\\Common Files\\Microsoft Shared\\OFFICE11\\MSO.DLL" rename( "RGB", "MSORGB" ) using namespace Office; #pragma warning(disable : 4192) #import "C:\\Program Files\\Common Files\\Microsoft Shared\\VBA\\VBA6\\VBE6EXT.OLB" #import "D:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE" \ rename( "DialogBox", "ExcelDialogBox" ) \ rename( "RGB", "ExcelRGB" ) \ rename( "CopyFile", "ExcelCopyFile" ) \ rename( "ReplaceText", "ExcelReplaceText" ) void CRecordView::OnFileExport() { TCHAR szFilter[] = { _T("Excel檔案 (*.xls)|*.xls|所有檔案 (*.*)|*.*||") }; CFileDialog SaveDialog(FALSE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, szFilter); if (SaveDialog.DoModal() == IDOK) { _variant_t varOption((long)DISP_E_PARAMNOTFOUND, VT_ERROR); CWaitCursor wait; try { Excel::_ApplicationPtr pExcelApp(_T("Excel.Application")); Excel::_WorkbookPtr pBook = pExcelApp->Workbooks->Add(varOption); Excel::_WorksheetPtr pSheet = pBook->ActiveSheet; //Excel::RangePtr pRange = pSheet->GetRange(_T("A1"), _T("D1")); Excel::RangePtr pRange = pSheet->Cells; CHeaderCtrl* pHeader = m_wndList.GetHeaderCtrl(); int nColumn = pHeader->GetItemCount(); { TCHAR szText[40] = { 0 }; HDITEM hdi = { 0 }; hdi.mask = HDI_TEXT; hdi.pszText = szText; hdi.cchTextMax = 40; for (int i = 1; i < nColumn; i++) { pHeader->GetItem(i, &hdi); pRange->Item[1][i] = hdi.pszText; } Excel::RangePtr pHeaderRange = pRange->GetRange(variant_t(_T("A1")), variant_t(_T("F1"))); pHeaderRange->Font->Bold = true; } for (int i = 0; i < m_wndList.GetItemCount(); i++) { for (int j = 1; j < nColumn; j++) { pRange->Item[i+2][j] = (LPCTSTR)m_wndList.GetItemText(i, j); } } pRange = pRange->EntireColumn; pRange->AutoFit(); pBook->Close(true, (LPCTSTR)SaveDialog.GetPathName(), varOption); pExcelApp->Quit(); AfxMessageBox(_T("資料已成功匯出到Excel表格中!"), MB_OK | MB_ICONINFORMATION); } catch (...) { AfxMessageBox(_T("匯出資料錯誤!"), MB_OK | MB_ICONERROR); return; } } }
轉載自 : http://www.cppblog.com/wangjs720/archive/2007/09/10/31934.html
匯出Excel的第二種方法用的是如下 :
CApplication app;
CWorkbook0 book;
CWorkbooks0 books;
CWorksheet0 sheet; CWorksheets0 sheets;
CRange0 range;
CListCtrl控制元件匯出excel大概步驟如下:
1.首先開啟vs2010,建一個專案(ExportExcel),建立完後點擊右鍵,新增--類--MFC--TypeLib中的MFC類,到該頁面點新增如下:
2.點新增完後,注意下,找到相關標頭檔案,註釋紅色那行
//#import "D:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE" no_namespace
// CWorkbook 包裝類
class CWorkbook : public COleDispatchDriver
{
public:
CWorkbook(){} // 呼叫 COleDispatchDriver 預設建構函式
CWorkbook(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {}
CWorkbook(const CWorkbook& dispatchSrc) : COleDispatchDriver(dispatchSrc) {}
3.註釋完後,把上面新增的類的標頭檔案加到你要實現匯出excel功能的類中,如下:
#include "CApplication.h"
#include "CRange.h"
#include "CWorkbooks.h"
#include "CWorksheets.h"
#include "CWorkbook.h"
#include "CWorksheet.h"
4.實現主要程式碼如下:
//匯出
void Cimportexcel2Dlg::OnBnClickedButton1()
{
CFileDialog FileDialog(FALSE,L"xls",NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
_T("Microsoft Excel 2000(*.xls)|*.xls|所有檔案(*.*)"),this);
if(FileDialog.DoModal()!=IDOK)
return;
CString cStrFile=FileDialog.GetPathName(); //選擇儲存路徑名稱
if(::PathFileExists(cStrFile))
DeleteFile(cStrFile);
//CString cStrFile = _T("E:\\myexcel.xls");
COleVariant covTrue((short)TRUE),covFalse((short)FALSE),covOptional((long)
DISP_E_PARAMNOTFOUND,VT_ERROR);
CApplication app; //Excel程式
CWorkbooks books; //工作簿集合
CWorkbook book; //工作表
CWorksheets sheets; //工作簿集合
CWorksheet sheet; //工作表集合
CRange range; //使用區域
CoUninitialize();
book.PrintPreview(_variant_t(false));
if(CoInitialize(NULL)==S_FALSE)
{
MessageBox(L"初始化COM支援庫失敗!");
return;
}
if(!app.CreateDispatch(_T("Excel.Application"))); //建立IDispatch介面物件
{
MessageBox(_T("Error!"));
}
books = app.get_Workbooks();
book = books.Add(covOptional);
sheets = book.get_Worksheets();
sheet = sheets.get_Item(COleVariant((short)1)); //得到第一個工作表
CHeaderCtrl* pmyHeaderCtrl= m_list.GetHeaderCtrl(); //獲取表頭
int m_cols = pmyHeaderCtrl-> GetItemCount(); //獲取列數
int m_rows = m_list.GetItemCount(); //獲取行數
TCHAR lpBuffer[256];
//此結構包含關於頭控制元件中的項的資訊,此結構已被更新以支援標題項影象和順序值。
HDITEM hdi;
hdi.mask = HDI_TEXT;
hdi.pszText = lpBuffer;
hdi.cchTextMax = 256;
CString colname;
CString strTemp;
int iRow,iCol;
for(iCol=0;iCol < m_cols;iCol++) //將列表的標題頭寫入EXCEL
{
GetCellName(1 ,iCol + 1, colname); //(colname就是對應表格的A1,B1,C1,D1)
range = sheet.get_Range(COleVariant(colname),COleVariant(colname));
pmyHeaderCtrl-> GetItem(iCol,&hdi); //獲取表頭每列的資訊
range.put_Value2(COleVariant(hdi.pszText)); //設定每列的內容
int nWidth = m_list.GetColumnWidth(iCol)/6;
//得到第iCol+1列
range.AttachDispatch(range.get_Item(_variant_t((long)(iCol+1)),vtMissing).pdispVal,true);
//設定列寬
range.put_ColumnWidth(_variant_t((long)nWidth));
}
range = sheet.get_Range(COleVariant(_T("A1")),COleVariant(colname));
range.put_RowHeight(_variant_t((long)50)); //設定行的高度
range.put_VerticalAlignment(COleVariant((short)-4108)); //xlVAlignCenter=-4108
COleSafeArray saRet; //COleSafeArray類是用於處理任意型別和維數的陣列的類
DWORD numElements[]={m_rows,m_cols}; //行列寫入陣列
saRet.Create(VT_BSTR,2,numElements); //建立所需的陣列
range = sheet.get_Range(COleVariant(_T("A2")),covOptional); //從A2開始
range = range.get_Resize(COleVariant((short)m_rows),COleVariant((short)m_cols)); //表的區域
long index[2];
//將列表內容寫入EXCEL
for(iRow = 1;iRow <= m_rows;iRow++)
{
for(iCol = 1;iCol <= m_cols;iCol++)
{
index[0]=iRow-1;
index[1]=iCol-1;
CString szTemp;
szTemp=m_list.GetItemText(iRow-1,iCol-1); //取得m_list控制元件中的內容
BSTR bstr = szTemp.AllocSysString(); //AlLogyString方法分配一個自動化相容的新BSTR字串。
saRet.PutElement(index,bstr); //把m_list控制元件中的內容放入saRet
SysFreeString(bstr);
}
}
range.put_Value2(COleVariant(saRet)); //將得到的資料的saRet陣列值放入表格
book.SaveCopyAs(COleVariant(cStrFile)); //儲存到cStrFile檔案
book.put_Saved(true);
books.Close();
book.ReleaseDispatch();
books.ReleaseDispatch();
app.ReleaseDispatch();
app.Quit();
}
5.新增完,程式碼編譯會出現錯誤,修改:雙擊提示,在DialogBox()前加下劃線,就可以了
6.重新編譯,OK
轉載自 : https://blog.csdn.net/qrx2013/article/details/12749333
轉載一下下面的連結,感覺文章寫的類似,程式碼比較全,但是註釋沒有上面的詳細.
轉載 : https://blog.csdn.net/limingmcu/article/details/38058507