C++ 读写 EXCEL
#include "stdafx.h"#include "ExcelOperate.h"
ExcelOperate::ExcelOperate()
{
}
ExcelOperate::~ExcelOperate()
{
}
BOOL ExcelOperate::CreateApp()
{
COleException pe;
//创建Excel 服务器(启动Excel)
if (!m_ExcelApp.CreateDispatch(_T("Excel.Application"), &pe))
{
AfxMessageBox(_T("启动Excel服务失败,请确保安装了excel 2000或以上版本!"), MB_OK | MB_ICONWARNING);
pe.ReportError();
throw& pe;
return FALSE;
}
m_ExcelApp.put_DisplayAlerts(FALSE);//屏蔽警告
//CString strExcelVersion = m_ExcelApp.get_Version();
return true;
}
BOOL ExcelOperate::CreateWorkbooks()
{
if (FALSE == CreateApp())
{
return FALSE;
}
m_ecBooks.AttachDispatch(m_ExcelApp.get_Workbooks());
if (!m_ecBooks.m_lpDispatch)
{
AfxMessageBox(_T("WorkBooks创建失败!"), MB_OK | MB_ICONWARNING);
return FALSE;
}
return TRUE;
}
BOOL ExcelOperate::CreateWorkbook()
{
if (!m_ecBooks.m_lpDispatch)
{
AfxMessageBox(_T("WorkBooks为空!"), MB_OK | MB_ICONWARNING);
return FALSE;
}
COleVariant vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
m_ecBook.AttachDispatch(m_ecBooks.Add(vtMissing));
if (!m_ecBook.m_lpDispatch)
{
AfxMessageBox(_T("WorkBook为空!"), MB_OK | MB_ICONWARNING);
return FALSE;
}
/*
//得到document变量
m_wdDoc = m_wdApp.GetActiveDocument();
if (!m_wdDoc.m_lpDispatch)
{
AfxMessageBox(_T("Document获取失败!"), MB_OK|MB_ICONWARNING);
return FALSE;
}
//得到selection变量
m_wdSel = m_wdApp.GetSelection();
if (!m_wdSel.m_lpDispatch)
{
AfxMessageBox(_T("Select获取失败!"), MB_OK|MB_ICONWARNING);
return FALSE;
}
//得到Range变量
m_wdRange = m_wdDoc.Range(vOptional,vOptional);
if(!m_wdRange.m_lpDispatch)
{
AfxMessageBox(_T("Range获取失败!"), MB_OK|MB_ICONWARNING);
return FALSE;
}
*/
return TRUE;
}
BOOL ExcelOperate::CreateWorksheets()
{
if (!m_ecBook.m_lpDispatch)
{
AfxMessageBox(_T("WorkBook为空!"), MB_OK | MB_ICONWARNING);
return FALSE;
}
m_ecSheets = m_ecBook.get_Sheets();
if (!m_ecSheets.m_lpDispatch)
{
AfxMessageBox(_T("WorkSheets为空!"), MB_OK | MB_ICONWARNING);
return FALSE;
}
return TRUE;
}
BOOL ExcelOperate::CreateWorksheet(short index)
{
if (!m_ecSheets.m_lpDispatch)
{
AfxMessageBox(_T("WorkSheets为空!"), MB_OK | MB_ICONWARNING);
return FALSE;
}
m_ecSheet = m_ecSheets.get_Item(COleVariant(index));
if (!m_ecSheet.m_lpDispatch)
{
AfxMessageBox(_T("WorkSheet为空!"), MB_OK | MB_ICONWARNING);
return FALSE;
}
//auto name= m_ecSheet.get_Name();
return TRUE;
/*打开一个Sheet,如不存在,就新增一个Sheet*/
//CString strSheetName = _T("NewSheet");
//try
//{
// /*打开一个已有的Sheet*/
// lpDisp = m_ecSheets.get_Item(_variant_t(strSheetName));
// m_ecSheet.AttachDispatch(lpDisp);
//}
//catch (...)
//{
// /*创建一个新的Sheet*/
// lpDisp = m_ecSheets.Add(vtMissing, vtMissing, _variant_t((long)1), vtMissing);
// m_ecSheet.AttachDispatch(lpDisp);
// m_ecSheet.put_Name(strSheetName);
//}
}
BOOL ExcelOperate::CreateSheet(short index)
{
if (CreateWorksheets() == FALSE)
{
return FALSE;
}
if (CreateWorksheet(index) == FALSE)
{
return FALSE;
}
return TRUE;
}
BOOL ExcelOperate::Create(short index)
{
if (CreateWorkbooks() == FALSE)
{
return FALSE;
}
if (CreateWorkbook() == FALSE)
{
return FALSE;
}
if (CreateSheet(index) == FALSE)
{
return FALSE;
}
return TRUE;
}
int ExcelOperate::GetSheetCount()
{
return m_ecSheets.get_Count();
}
BOOL ExcelOperate::LoadSheet(const CString& sheet)
{
if (!m_ecSheets.m_lpDispatch)
{
AfxMessageBox(_T("WorkSheets为空!"), MB_OK | MB_ICONWARNING);
return FALSE;
}
m_ecSheet = m_ecSheets.get_Item(COleVariant(sheet));
if (!m_ecSheet.m_lpDispatch)
{
AfxMessageBox(_T("WorkSheet为空!"), MB_OK | MB_ICONWARNING);
return FALSE;
}
//auto name= m_ecSheet.get_Name();
return TRUE;
}
void ExcelOperate::ShowApp()
{
m_ExcelApp.put_Visible(true);
m_ExcelApp.put_DisplayFullScreen(true);//设置全屏显示
//m_ExcelApp.put_UserControl(FALSE);
}
void ExcelOperate::HideApp()
{
m_ExcelApp.put_Visible(FALSE);
//m_ExcelApp.put_CutCopyMode(false);
//m_ExcelApp.put_UserControl(FALSE);
}
BOOL ExcelOperate::OpenWorkbook(const CString& fileName, short index)
{
if (!m_ecBooks.m_lpDispatch)
{
AfxMessageBox(_T("WorkSheets为空!"), MB_OK | MB_ICONWARNING);
return FALSE;
}
//COleVariant vFileName(_T(fileName));
COleVariant VOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
m_ecBook = m_ecBooks.Open(fileName, VOptional, VOptional, VOptional, VOptional, VOptional, VOptional, VOptional, VOptional, VOptional, VOptional, VOptional, VOptional, VOptional, VOptional);
if (!m_ecBook.m_lpDispatch)
{
AfxMessageBox(_T("WorkSheet获取失败!"), MB_OK | MB_ICONWARNING);
return FALSE;
}
if (CreateSheet(index) == FALSE)
{
return FALSE;
}
return TRUE;
}
BOOL ExcelOperate::Open(const CString& fileName)
{
if (CreateWorkbooks() == FALSE)
{
return FALSE;
}
return OpenWorkbook(fileName);
}
BOOL ExcelOperate::SetActiveWorkbook(short& i)
{
return 0;
}
BOOL ExcelOperate::SaveWorkbook()
{
if (!m_ecBook.m_lpDispatch)
{
//AfxMessageBox(_T("Book获取失败!"), MB_OK | MB_ICONWARNING);
return FALSE;
}
m_ecBook.Save();
return TRUE;
}
BOOL ExcelOperate::SaveWorkbookAs(const CString& fileName)
{
if (!m_ecBook.m_lpDispatch)
{
AfxMessageBox(_T("Book获取失败!"), MB_OK | MB_ICONWARNING);
return FALSE;
}
COleVariant vTrue((short)TRUE),
vFalse((short)FALSE),
vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
COleVariant vFileName(fileName);
long XlFileFormat = 51;
CString strSuffix = fileName.Mid(fileName.ReverseFind(_T('.')));
if (0 == strSuffix.CompareNoCase(_T(".xls")))
{
XlFileFormat = 56;
}
m_ecBook.SaveAs(
vFileName, //VARIANT* FileName
_variant_t(XlFileFormat), //VARIANT* FileFormat
vtMissing, //VARIANT* LockComments
vtMissing, //VARIANT* Password
vtMissing, //VARIANT* AddToRecentFiles
vtMissing, //VARIANT* WritePassword
0, //VARIANT* ReadOnlyRecommended
vtMissing, //VARIANT* EmbedTrueTypeFonts
vtMissing, //VARIANT* SaveNativePictureFormat
vtMissing, //VARIANT* SaveFormsData
vtMissing, //VARIANT* SaveAsAOCELetter
vtMissing //VARIANT* ReadOnlyRecommended
);
return TRUE;
}
BOOL ExcelOperate::CloseWorkbook()
{
COleVariant vTrue((short)TRUE),
vFalse((short)FALSE),
vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
m_ecBook.Close(vFalse, // SaveChanges.
vTrue, // OriginalFormat.
vFalse // RouteDocument.
);
m_ecBook = m_ExcelApp.get_ActiveWorkbook();
if (!m_ecBook.m_lpDispatch)
{
//AfxMessageBox(_T("Book获取失败!"), MB_OK | MB_ICONWARNING);
return FALSE;
}
if (CreateSheet(1) == FALSE)
{
return FALSE;
}
return TRUE;
}
void ExcelOperate::CloseApp()
{
SaveWorkbook();
COleVariant vTrue((short)TRUE),
vFalse((short)FALSE),
vOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
//m_ecDoc.Save();
if (m_ecRange.m_lpDispatch)
m_ecRange.ReleaseDispatch();
if (m_ecSheet.m_lpDispatch)
m_ecSheet.ReleaseDispatch();
if (m_ecSheets.m_lpDispatch)
m_ecSheets.ReleaseDispatch();
if (m_ecBook.m_lpDispatch)
m_ecBook.ReleaseDispatch();
if (m_ecBooks.m_lpDispatch)
m_ecBooks.ReleaseDispatch();
m_ExcelApp.Quit();
if (m_ExcelApp.m_lpDispatch)
m_ExcelApp.ReleaseDispatch();
}
void ExcelOperate::MergeRange(const CString& begin, const CString& end)
{
if (!m_ecSheet.m_lpDispatch)
{
AfxMessageBox(_T("Sheet获取失败!"), MB_OK | MB_ICONWARNING);
return;
}
m_ecRange = m_ecSheet.get_Range(COleVariant(begin), COleVariant(end));
if (!m_ecRange.m_lpDispatch)
{
AfxMessageBox(_T("Range获取失败!"), MB_OK | MB_ICONWARNING);
return;
}
m_ecRange.Merge(_variant_t((long)0));
//m_ecRange.put_HorizontalAlignment(_variant_t((long)-4108)); //水平居中对齐
//m_ecRange.put_VerticalAlignment(_variant_t((long)-4108)); //竖直居中对齐
//m_ecRange.put_ColumnWidth(_variant_t(20)); //列宽
//m_ecRange.put_RowHeight(COleVariant(_T("25"))); //行高
//ft.AttachDispatch(m_ecRange.get_Font()); //匹配
//ft.put_Bold(_variant_t((long)1)); //设置粗体,0-不加粗;1-加粗
//ft.put_Italic(_variant_t((long)1)); //设置斜体,0-不斜;1-斜
//ft.put_Size(_variant_t((long)18)); //字大小
//ft.put_ColorIndex(_variant_t((long)5)); //字颜色
//it.AttachDispatch(m_ecRange.get_Interior());
//it.put_ColorIndex(_variant_t((long)8)); //背景色
//m_ecRange.BorderAround(_variant_t((long)1), _variant_t((long)2), _variant_t((long)1), vtMissing, vtMissing);//线型 // 线宽 //颜色
}
bool ExcelOperate::InsertRow(const long& row, const long& column)
{
if (!m_ecSheet.m_lpDispatch)
{
AfxMessageBox(_T("Sheet获取失败!"), MB_OK | MB_ICONWARNING);
return FALSE;
}
m_ecRange = m_ecSheet.get_Cells();
if (!m_ecRange.m_lpDispatch)
{
AfxMessageBox(_T("Range获取失败!"), MB_OK | MB_ICONWARNING);
return false;
}
m_ecRange.AttachDispatch(m_ecRange.get_Item(COleVariant(row), COleVariant(column)).pdispVal, true);
//CRange cols = m_ecRange.get_EntireColumn();//获取列
//cols.AutoFit();
CRange cols = m_ecRange.get_EntireRow();
cols.Insert(vtMissing, _variant_t(1));//0是复制上面行格式,1是当前行
cols.ReleaseDispatch();
return true;
}
void ExcelOperate::SetRangeAndValue(const CString& begin, const CString& end, const CString& value)
{
if (!m_ecSheet.m_lpDispatch)
{
AfxMessageBox(_T("Sheet获取失败!"), MB_OK | MB_ICONWARNING);
return;
}
m_ecRange = m_ecSheet.get_Range(COleVariant(begin), COleVariant(end));
if (!m_ecRange.m_lpDispatch)
{
AfxMessageBox(_T("Range获取失败!"), MB_OK | MB_ICONWARNING);
return;
}
m_ecRange.put_Value2(COleVariant(value));
}
void ExcelOperate::SetRangeAndValue(const long& row, const long& column, const CString& value)
{
if (!m_ecSheet.m_lpDispatch)
{
AfxMessageBox(_T("Sheet获取失败!"), MB_OK | MB_ICONWARNING);
return;
}
m_ecRange = m_ecSheet.get_Cells();
if (!m_ecRange.m_lpDispatch)
{
AfxMessageBox(_T("Range获取失败!"), MB_OK | MB_ICONWARNING);
return;
}
m_ecRange.put_Item(COleVariant(row), COleVariant(column), COleVariant(value));
//m_ecRange.AttachDispatch(m_ecSheet.get_UsedRange());//加载已使用的单元格
//m_ecRange.put_WrapText(_variant_t((long)1));//设置单元格内的文本为自动换行
//m_ecRange.put_HorizontalAlignment(_variant_t((long)-4108));//水平居中
//m_ecRange.put_VerticalAlignment(_variant_t((long)-4108));//垂直居中
}
void ExcelOperate::SetRangeAndValue(const long& row, const long& column, const int& value)
{
if (!m_ecSheet.m_lpDispatch)
{
AfxMessageBox(_T("Sheet获取失败!"), MB_OK | MB_ICONWARNING);
return;
}
m_ecRange = m_ecSheet.get_Cells();
if (!m_ecRange.m_lpDispatch)
{
AfxMessageBox(_T("Range获取失败!"), MB_OK | MB_ICONWARNING);
return;
}
m_ecRange.put_Item(COleVariant(row), COleVariant(column), _variant_t(value));
}
BOOL ExcelOperate::GetRangeAndValue(const CString& begin, const CString& end)
{
if (!m_ecSheet.m_lpDispatch)
{
AfxMessageBox(_T("Sheet获取失败!"), MB_OK | MB_ICONWARNING);
return FALSE;
}
m_ecRange = m_ecSheet.get_Range(COleVariant(begin), COleVariant(end));
if (!m_ecRange.m_lpDispatch)
{
AfxMessageBox(_T("Range获取失败!"), MB_OK | MB_ICONWARNING);
return FALSE;
}
ret = m_ecRange.get_Value2();//得到表格中的值
return TRUE;
}
BOOL ExcelOperate::GetRangeAndValue(const long& row, const long& column)
{
if (!m_ecSheet.m_lpDispatch)
{
AfxMessageBox(_T("Sheet获取失败!"), MB_OK | MB_ICONWARNING);
return FALSE;
}
m_ecRange = m_ecSheet.get_Cells();
if (!m_ecRange.m_lpDispatch)
{
AfxMessageBox(_T("Range获取失败!"), MB_OK | MB_ICONWARNING);
return false;
}
//CRange range;
//range.AttachDispatch(m_ecRange.get_Item(COleVariant(row), COleVariant(column)).pdispVal, true);
m_ecRange.AttachDispatch(m_ecRange.get_Item(COleVariant(row), COleVariant(column)).pdispVal, true);
ret = m_ecRange.get_Value2();//得到表格中的值
return TRUE;
}
void ExcelOperate::GetRowsAndCols(long& rows, long& cols)
{
COleSafeArray sa(ret);
sa.GetUBound(1, &rows);
sa.GetUBound(2, &cols);
}
BOOL ExcelOperate::GetTheValue(const int& rows, const int& cols, CString& dest)
{
/*long rRows, rCols;
long index;
VARIANT val;
COleSafeArray sa(ret);
sa.GetUBound(1, &rRows);
sa.GetUBound(2, &rCols);
if (rows < 1 || cols < 1 || rRows < rows || rCols < cols)
{
AfxMessageBox(_T("行列不在范围"));
return FALSE;
}
index = rows;
index = cols;
sa.GetElement(index, &val);
if (val.vt != VT_BSTR)
{
CString str;
str.Format(_T("出错点2, %d"), val.vt);
AfxMessageBox(str);
return FALSE;
}
dest = val.bstrVal;
return TRUE;*/
if (!m_ecSheet.m_lpDispatch)
{
AfxMessageBox(_T("Sheet获取失败!"), MB_OK | MB_ICONWARNING);
return FALSE;
}
m_ecRange = m_ecSheet.get_Cells();
if (!m_ecRange.m_lpDispatch)
{
AfxMessageBox(_T("Range获取失败!"), MB_OK | MB_ICONWARNING);
return false;
}
CRange range;
range.AttachDispatch(m_ecRange.get_Item(COleVariant((long)rows), COleVariant((long)cols)).pdispVal, true);
ret = range.get_Value2();
range.ReleaseDispatch();
if (ret.vt == VT_BSTR)
{
dest = ret.bstrVal;
}
//整数
else if (ret.vt == VT_INT)
{
dest.Format(_T("%d"), ret.pintVal);
}
//8字节的数字
else if (ret.vt == VT_R8)
{
dest.Format(_T("%.2lf"), ret.dblVal);
}
//时间格式
else if (ret.vt == VT_DATE)
{
SYSTEMTIME st;
VariantTimeToSystemTime(ret.date, &st);
CTime tm(st);
dest = tm.Format(_T("%Y-%m-%d"));
}
//单元格空的
else if (ret.vt == VT_EMPTY)
{
dest = "";
}
return TRUE;
}
BOOL ExcelOperate::SetTextFormat(const CString& beginS, const CString& endS)
{
if (GetRangeAndValue(beginS, endS))
{
m_ecRange.Select();
m_ecRange.put_NumberFormatLocal(COleVariant(_T("@")));
return TRUE;
}
return FALSE;
}
BOOL ExcelOperate::SetTextFormat(long& row, long& column)
{
if (GetRangeAndValue(row, column))
{
m_ecRange.Select();
m_ecRange.put_NumberFormatLocal(COleVariant(_T("@")));
return TRUE;
}
return FALSE;
}
BOOL ExcelOperate::SetRowToTextFormat(const CString& beginS, const CString& endS)
{
if (GetRangeAndValue(beginS, endS))
{
m_ecRange.Select();
CRange m_tempRange = m_ecSheet.get_Range(COleVariant(beginS), COleVariant(beginS));
if (!m_tempRange.m_lpDispatch) return FALSE;
COleVariant vTrue((short)TRUE),
vFalse((short)FALSE);
//int tempArray = {1, 2};
COleSafeArray saRet;
DWORD numElements = { 2 };
saRet.Create(VT_I4, 1, &numElements);
long index = 0;
int val = 1;
saRet.PutElement(&index, &val);
index++;
val = 2;
saRet.PutElement(&index, &val);
//m_tempRange.GetItem(COleVariant((short)5),COleVariant("A"));
m_ecRange.TextToColumns(m_tempRange.get_Item(COleVariant((short)1), COleVariant((short)1)), 1, 1, vFalse, vTrue, vFalse, vFalse, vFalse, vFalse, vFalse, saRet, vFalse, vFalse, vTrue);
m_tempRange.ReleaseDispatch();
return TRUE;
}
return FALSE;
}
#pragma once
#include "msexcel/CApplication0.h"
#include "msexcel/CWorkbook.h"
#include "msexcel/CWorkbooks.h"
#include "msexcel/CWorksheet.h"
#include "msexcel/CWorksheets.h"
#include "msexcel/CRange.h"
#include "msexcel/CFont1.h"
#include "msexcel/Cnterior0.h"
class ExcelOperate
{
public:
ExcelOperate();
~ExcelOperate();
//创建一个新的EXCEL应用程序
BOOL CreateApp();
//创建一个新的EXCEL工作簿集合
BOOL CreateWorkbooks();
//创建一个新的EXCEL工作簿
BOOL CreateWorkbook();
//创建一个新的EXCEL工作表集合
BOOL CreateWorksheets();
//创建一个新的EXCEL工作表
BOOL CreateWorksheet(short index);
BOOL CreateSheet(short index);
//创建新的EXCEL应用程序并创建一个新工作簿和工作表
BOOL Create(short index = 1);
//得到Sheet的总数
int GetSheetCount();
//通过名称使用某个sheet,
BOOL LoadSheet(const CString& sheet);
//显示EXCEL文档
void ShowApp();
//隐藏EXCEL文档
void HideApp();
BOOL OpenWorkbook(const CString& fileName, short index = 1);
//创建新的EXCEL应用程序并打开一个已经存在的文档。
BOOL Open(const CString& fileName);
//设置当前激活的文档。
BOOL SetActiveWorkbook(short& i);
//Excel是以打开形式,保存。
BOOL SaveWorkbook();
//Excel以创建形式,保存。
BOOL SaveWorkbookAs(const CString& fileName);
/// <summary>
/// 关闭
/// </summary>
/// <returns></returns>
BOOL CloseWorkbook();
/// <summary>
/// 退出
/// </summary>
void CloseApp();
//合并单元格
void MergeRange(const CString& begin, const CString& end);
//插入行
bool InsertRow(const long& row, const long& column);
//设置值
void SetRangeAndValue(const CString& begin, const CString& end, const CString& value);
void SetRangeAndValue(const long& row, const long& column, const CString& value);
void SetRangeAndValue(const long& row, const long& column, const int& value);
//得到begin到end的Range并将之间的值设置到ret中
BOOL GetRangeAndValue(const CString& begin, const CString& end);
BOOL GetRangeAndValue(const long& row, const long& column);
//得到ret的行,列数
void GetRowsAndCols( long& rows,long& cols);
//返回第rows,cols列的值,注意只返回文本类型的,到dest中
BOOL GetTheValue(const int& rows,const int& cols, CString& dest);
//将beginS到endS设置为文本格式(数字的还要用下面的方法再转一次)
BOOL SetTextFormat(const CString& beginS, const CString& endS);
BOOL SetTextFormat(long& row, long& column);
//将beginS到endS(包括数字类型)设置为文本格式
BOOL SetRowToTextFormat(const CString& beginS, const CString& endS);
private:
CApplication0 m_ExcelApp;
CWorkbooks m_ecBooks;
CWorkbook m_ecBook;
CWorksheets m_ecSheets;
CWorksheet m_ecSheet;
CRange m_ecRange;
CFont1 ft;//定义字体变量
Cnterior it; //定义背景色变量
VARIANT ret;//保存单元格的值
LPDISPATCH lpDisp;
};
页:
[1]