一个vc的clistctrl的数据写到excel的方法

来源:岁月联盟 编辑:exp 时间:2012-02-07
首先包含头文件和初始化COM接口,一定记得初始化com啊,调用CoInitialize(NULL);
 
#include <odbcinst.h>
#include <afxdb.h>
#include <comdef.h>
void ExportListToExcel(CListCtrl *pList, CString sExcelFile, CString sSheetName)
{
_Worksheet m_wsExcelSingle;
Worksheets m_wsExcels;
_Workbook m_wbExcelSingle;
Workbooks m_wbExcels;
_Application m_appExcel;
    Range m_rangeExcel;
 
COleVariant covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
 
if (!m_appExcel.CreateDispatch("Excel.Application",NULL))
{
MessageBox("创建Excel服务失败!","提示",MB_OK|MB_ICONWARNING);
return;
}
 
m_appExcel.SetVisible(false);
m_wbExcels.AttachDispatch(m_appExcel.GetWorkbooks(),true);
 
m_wbExcelSingle.AttachDispatch(m_wbExcels.Add(covOptional));
 
//得到Worksheets
m_wsExcels.AttachDispatch(m_wbExcelSingle.GetWorksheets(),true);
//删除多余的表
m_wsExcelSingle.AttachDispatch(m_wsExcels.GetItem(COleVariant((short)3)));
m_wsExcelSingle.Delete();
m_wsExcelSingle.AttachDispatch(m_wsExcels.GetItem(COleVariant((short)2)));
m_wsExcelSingle.Delete();
//表改名
m_wsExcelSingle.AttachDispatch(m_wsExcels.GetItem(COleVariant((short)1)));
m_wsExcelSingle.SetName(sSheetName);
m_rangeExcel.AttachDispatch(m_wsExcelSingle.GetUsedRange(), TRUE);
 
if (pList->GetItemCount ()>0)  
{
int nItemCount,nColumnCount;
 
nColumnCount = pList->GetHeaderCtrl()->GetItemCount();
nItemCount = pList->GetItemCount();
int i;
LVCOLUMN columnData;
CString columnName;
int columnNum = 0;
CString strH;
CString strV;
 
columnData.mask = LVCF_TEXT;
columnData.cchTextMax =100;
columnData.pszText = columnName.GetBuffer (100);
//写列表头
for(i=0;pList->GetColumn(i,&columnData);i++)
{
   m_rangeExcel.SetItem( _variant_t( (long)(1) ), _variant_t( (long)(i+1) ),COleVariant(columnData.pszText) );
}
columnName.ReleaseBuffer ();
 
// 向Excel中写数据
for (i = 0; i < nItemCount; i++ )            
{
   for ( int j = 0; j < nColumnCount; j++ )
   {
    m_rangeExcel.SetItem( _variant_t( (long)(i+2) ),
     _variant_t( (long)(j+1) ),
     COleVariant(pList->GetItemText(i,j)) );
   }
}
 
//此方法对于不同的Excel版本参数个数可能不能,具体参看MSDN
m_wbExcelSingle.SaveAs( COleVariant( sExcelFile ),
   _variant_t(vtMissing),
   _variant_t(vtMissing),
   _variant_t(vtMissing),
   _variant_t(vtMissing),
   _variant_t(vtMissing),
   0,
   _variant_t(vtMissing),
   _variant_t(vtMissing),
   _variant_t(vtMissing),
   _variant_t(vtMissing));
 
}
else
{
//没有数据
MessageBox("没有数据,不能导出!","提示",MB_OK|MB_ICONWARNING|MB_TOPMOST);
 
}
 
 
m_wbExcelSingle.Close( covOptional, COleVariant( sExcelFile ), covOptional );
m_wbExcels.Close();
m_rangeExcel.ReleaseDispatch();
m_wsExcelSingle.ReleaseDispatch();
m_wsExcels.ReleaseDispatch();
m_wbExcelSingle.ReleaseDispatch();
m_wbExcels.ReleaseDispatch();
m_appExcel.ReleaseDispatch();
m_appExcel.Quit();
 
}
 
 
再提供一个类
 
 
 
#pragma once
 
 
#include "StdAfx.h"
#include <iostream>
 
 
using namespace std ;
 
 
 
 
#import "C:/Program Files/Common Files/Microsoft Shared/OFFICE11/mso.dll" rename("RGB", "MSRGB")
 
 
#import "C:/Program Files/Common Files/Microsoft Shared/VBA/VBA6/VBE6EXT.OLB" raw_interfaces_only, /
rename("Reference", "ignorethis"), rename("VBE", "JOEVBE")
 
 
#import "C:/Program Files/Microsoft Office/OFFICE11/excel.exe" exclude("IFont", "IPicture") /
rename("RGB", "ignorethis"), rename("DialogBox", "ignorethis"), rename("VBE", "JOEVBE"), /
rename("ReplaceText", "JOEReplaceText"), rename("CopyFile","JOECopyFile"), /
rename("FindText", "JOEFindText"), rename("NoPrompt", "JOENoPrompt")
 
 
using namespace Office;
using namespace VBIDE;
using namespace Excel ;
 
 
 
 
#define NULLSTR TEXT("")
 
 
class CEclOp
{
public:
CEclOp(void);
~CEclOp(void);
public:
 
 
BOOL InsertAChart(short nSheet);
BOOL DeleteASheetByNO(short nSheet);
BOOL DeleteASheetByName(CString strSheet);
CString GetCellText(short nSheet, int Row, int Col);
void DeleteCells(short nSheet, CString strRange);
void DeleteCells(short nSheet, unsigned int nFRow, unsigned int nFCol, unsigned int nTRow, unsigned int nTCol);
BOOL Initialization(CString strFilePath = NULLSTR);
void SetCellText(short nsheet,int row, int col, _variant_t content);
void SetCellText(short nSheet,CString strCell, _variant_t Content);
void InsertPicsFromFile(LPCSTR path, short nsheet, double left, double top);
void InsertSheetsAfter(short nsheet, int num);
void SetColumnWidth(int nColF, int nColT, double dWidth);
void SaveQuit(CString strPath);
void ReleaseAllInterfaces();
void SetCellColor(short nSheet, CString Range, COLORREF rgb);
void SetCellColor(short nSheet, int row, int col, COLORREF rgb);
 
 
private:
int m_nTotalSheets;
int m_nCurSheet;
public:
_ApplicationPtr pApplication;
_WorkbookPtr pThisWorkbook;
_WorksheetPtr pThisWorksheet;
RangePtr pThisRange;
_variant_t vt ;
Excel::XlFileFormat vFileFormat ;
Excel::XlSaveAsAccessMode vSaveAsAccessMode ;
Excel::XlSaveConflictResolution vSaveConflictResolution ;
public:
SheetsPtr pThisSheets;
 
 
};
 
//cpp
 
/*EclOp.cpp*/
 
 
#include "stdafx.h"
#include "ExcelOprator.h"
 
 
 
 
CEclOp::CEclOp(void)
{
 
 
}
 
 
CEclOp::~CEclOp(void)
{
 
 
pThisRange.Release();
pThisRange.Release();                                       
pThisWorksheet.Release();                                      
pThisSheets.Release();                                        
pThisWorkbook.Release();                                     
pThisWorkbook.Release();                              
pApplication.Release();
::CoUninitialize();
}
 
 
void CEclOp::ReleaseAllInterfaces()
{
if (pThisRange != NULL)
pThisRange.Release();                                     
if (pThisWorksheet != NULL)
pThisWorksheet.Release();                                        
if (pThisSheets != NULL)
pThisSheets.Release();                                         
if (pThisWorkbook != NULL)
pThisWorkbook.Release();                                       
if (pApplication != NULL)
pApplication.Release();
 
 
::CoUninitialize();
}
BOOL CEclOp::Initialization(CString strPath)
{
 
 
if(FAILED(::CoInitialize(NULL)))
{
AfxMessageBox(TEXT("Initializing Excel Failed!"));
return FALSE;
}
pApplication = NULL;
pThisWorkbook = NULL;
pThisWorksheet = NULL;
pThisSheets = NULL;
pThisRange = NULL;
 
 
if (pApplication.CreateInstance(TEXT("Excel.Application")) != S_OK)
return FALSE;
//pApplication->PutVisible (0,VARIANT_TRUE);
pThisWorkbook = pApplication->GetWorkbooks()->Add((_variant_t)strPath) ;
pThisSheets = pThisWorkbook->GetWorksheets() ;
return TRUE;
}
 
 
void CEclOp::SetColumnWidth(int nColF, int nColT, double dWidth)
{
CString strRange;
strRange.Format(TEXT("%c%d:%c%d"), nColF + 'A' - 1, 1, nColT + 'A'- 1, 1 );
pThisRange = pThisWorksheet->GetRange((_variant_t)strRange);
pThisRange->GetEntireColumn()->ColumnWidth = dWidth;
 
 
}
 
 
 
 
void CEclOp::SetCellText(short nSheet,CString strCell, _variant_t Content)
{
 
 
// pThisWorksheet = pThisSheets->GetItem(nSheet);
// pThisRange = pThisWorksheet->GetRange(COleVariant(strCell),   COleVariant(strCell));
 
 
CString strRange;
 
 
pThisWorksheet = pThisSheets->GetItem(nSheet);
 
 
// strRange.Format("%c%d:%c%d", Col + 'A' - 1, Row, Col + 'A'- 1, Row );//need to confirm;
 
 
strRange = strCell + ":" + strCell;
 
 
pThisRange = pThisWorksheet->GetRange((_variant_t)strRange);
 
 
pThisRange->PutItem(1, 1, Content);
 
 
}
 
 
CString CEclOp::GetCellText(short nSheet, int Row, int Col)
{
CString strRet;
CString strRange;
pThisWorksheet = pThisSheets->GetItem(nSheet);
 
 
if (Col <= 26)
strRange.Format(TEXT("%c%d:%c%d"), Col + 'A' - 1, Row, Col + 'A'- 1, Row );//need to confirm;
else //if (Col > 26 && Col <= 256)//max columns of an excel sheet is 256
{
char chCol = Col % 26 + 'A' - 1 < 'A' ? 'Z':Col % 26 + 'A' - 1;
strRange.Format(TEXT("%c%c%d:%c%c%d"), (Col-1) / 26 + 'A' - 1, chCol, Row, (Col-1)/ 26 + 'A' - 1, chCol, Row);
}
 
 
pThisRange = pThisWorksheet->GetRange((_variant_t)strRange);
 
 
strRet = pThisRange->GetText();
 
 
return strRet;
}
 
 
void CEclOp::SetCellText(short nSheet,int Row, int Col, _variant_t Content)
{
 
 
CString strRange;
int nColStart = 1;
 
 
pThisWorksheet = pThisSheets->GetItem(nSheet);
 
 
if (Col <= 26)
strRange.Format(TEXT("%c%d:%c%d"), Col + 'A' - 1, Row, Col + 'A'- 1, Row );//need to confirm;
else //if (Col > 26 && Col <= 256)//max columns of an excel sheet is 256
{
char chCol = Col % 26 + 'A' - 1 < 'A' ? 'Z':Col % 26 + 'A' - 1;
strRange.Format(TEXT("%c%c%d:%c%c%d"), (Col-1) / 26 + 'A' - 1, chCol, Row, (Col-1)/ 26 + 'A' - 1, chCol, Row);
}
 
 
pThisRange = pThisWorksheet->GetRange((_variant_t)strRange);
pThisRange->PutItem(1, nColStart, Content);
 
 
}
 
 
void CEclOp::InsertPicsFromFile(LPCSTR path, short nSheet, double left, double top)
{
pThisWorksheet = pThisSheets->GetItem((_variant_t)nSheet);
 
 
PicturesPtr pics = pThisWorksheet->Pictures();
 
 
pics->Insert(path, VARIANT_FALSE);
pics->PutLeft(left);
pics->PutTop(top);
 
 
}
 
 
void CEclOp::InsertSheetsAfter(short nSheet, int nNum)
{
_WorksheetPtr pSheet = pThisSheets->GetItem(nSheet);
VARIANT var;
 
 
var.vt = VT_DISPATCH;
var.pdispVal = pSheet;
 
 
pThisSheets->Add(vtMissing,var,nNum);
 
 
}
 
 
void CEclOp::SaveQuit(CString strPath)
{
 
 
vSaveAsAccessMode = xlNoChange ;
vFileFormat = xlWorkbookNormal ;
vSaveConflictResolution = xlLocalSessionChanges ;
 
 
pThisWorkbook->SaveAs(_variant_t(strPath), vFileFormat,_variant_t(""),_variant_t(""), _variant_t(false),
_variant_t(false), vSaveAsAccessMode, vSaveConflictResolution, _variant_t(false)) ;
pThisWorkbook->Close();
pApplication->Quit();
}
 
 
void CEclOp::SetCellColor(short nSheet, CString strRange, COLORREF rgb)
{
pThisWorksheet = pThisSheets->GetItem((_variant_t)nSheet);
pThisWorksheet->GetRange((_variant_t)strRange)->GetInterior()->PutColor(rgb);
}
 
 
void CEclOp::SetCellColor(short nSheet, int row, int col, COLORREF rgb)
{
pThisWorksheet = pThisSheets->GetItem((_variant_t)nSheet);
CString strRange;
strRange.Format(TEXT("%c%d:%c%d"), 'A' + col - 1, row, 'A' + col - 1, row);
pThisWorksheet->GetRange((_variant_t)strRange)->GetInterior()->PutColor(rgb);
 
 
}
 
 
void CEclOp::DeleteCells(short nSheet, CString strRange)
{
pThisWorksheet = pThisSheets->GetItem((_variant_t)nSheet);
 
 
pThisRange = pThisWorksheet->GetRange((_variant_t)strRange);
 
 
pThisRange->Delete();
}
 
 
void CEclOp::DeleteCells(short nSheet, unsigned int nFRow, unsigned int nFCol, unsigned int nTRow, unsigned int nTCol)
{
pThisWorksheet = pThisSheets->GetItem((_variant_t)nSheet);
 
 
CString strRange;
 
 
if (nTCol <= 26)
strRange.Format(TEXT("%c%d:%c%d"), nFCol + 'A' - 1, nFRow, nTCol + 'A'- 1, nTRow);//need to confirm;
else //if (Col > 26 && Col <= 256)//max columns of an excel sheet is 256
{
char chTCol = nTCol % 26 + 'A' - 1 < 'A' ? 'Z':nTCol % 26 + 'A' - 1;
strRange.Format(TEXT("%c%d:%c%c%d"), nFCol + 'A' - 1, nFRow, (nTCol-1)/ 26 + 'A' - 1, chTCol, nTRow);
}
 
 
 
 
// strRange.Format("%c%d:%c%d", 'A' + nFCol - 1, nFRow, 'A' + nTCol - 1, nTRow);
pThisRange = pThisWorksheet->GetRange((_variant_t)strRange);
// pThisRange = pThisWorksheet->GetRange("H13:DB1004");
pThisRange->Delete();
 
 
 
 
}
 
 
BOOL CEclOp::DeleteASheetByNO(short nSheet)
{
_WorksheetPtr pSheet = pThisSheets->GetItem(nSheet);
pApplication->DisplayAlerts[0] = FALSE;
pThisWorksheet = pThisSheets->GetItem((_variant_t)nSheet);
pThisWorksheet->Delete();
return TRUE;
}
 
 
BOOL CEclOp::DeleteASheetByName(CString strSheet)
{
 
 
pApplication->DisplayAlerts[0] = FALSE;
//pThisWorksheet->AttachDispatch(pThisSheets->GetItem(COleVariant("Plot")));
pThisWorksheet = pThisSheets->GetItem(COleVariant(TEXT("Plot")));
pThisWorksheet->Delete();
return TRUE;
 
 
}
 
 
BOOL CEclOp::InsertAChart(short nSheet)
{
_ChartPtr pChart;
_WorksheetPtr pSheet = pThisSheets->GetItem(nSheet);
 
 
//_ChartPtr pChart = pThisWorkbook->Charts>Add();
pChart = pThisWorkbook->Charts->Add();
pChart->PutChartType(xlXYScatterLinesNoMarkers);
 
 
SeriesCollectionPtr pSeriesCollection;
SeriesPtr pSeries;
RangePtr pRange;
pThisWorksheet = pThisSheets->GetItem((_variant_t)nSheet);
pSeriesCollection= pChart->SeriesCollection();
pSeries = pSeriesCollection->NewSeries();
pRange = pThisWorksheet->Range["F2"]["F50"];
pSeries->PutXValues((Range*)pRange);
 
 
pChart->Location(xlLocationAsObject, pSheet->GetName());
 
 
return TRUE;
 
 
}
摘自 v2x222的专栏