整理了下网上的方法
工程设置
工程 - 属性 - 常规 - MFC的使用 在静态库中使用MFC
工程 - 属性 - 常规 - 字符集 使用多字节字符集
#include <iostream>
#include "excel9.h"
using namespace std;
using namespace excel;
#ifdef WIN32
#define uint8_t unsigned __int8
#define uint16_t unsigned __int16
#define uint32_t unsigned __int32
#define uint64_t unsigned __int64
#define int8_t __int8
#define int16_t __int16
#define int32_t __int32
#endif
// 4-11
int unicode_to_utf8(uint16_t *in, int insize, uint8_t **out)
{
int i = 0;
int outsize = 0;
int charscount = 0;
uint8_t *result = NULL;
uint8_t *tmp = NULL;
charscount = insize / sizeof(uint16_t);
result = (uint8_t *)malloc(charscount * 3 + 1);
memset(result, 0, charscount * 3 + 1);
tmp = result;
for (i = 0; i < charscount; i++)
{
uint16_t unicode = in[i];
if (unicode >= 0x0000 && unicode <= 0x007f)
{
*tmp = (uint8_t)unicode;
tmp += 1;
outsize += 1;
}
else if (unicode >= 0x0080 && unicode <= 0x07ff)
{
*tmp = 0xc0 | (unicode >> 6);
tmp += 1;
*tmp = 0x80 | (unicode & (0xff >> 2));
tmp += 1;
outsize += 2;
}
else if (unicode >= 0x0800 && unicode <= 0xffff)
{
*tmp = 0xe0 | (unicode >> 12);
tmp += 1;
//test 4-11
*tmp = 0x80 | ( (unicode >> 6) & 0x3f );//0x80 | (unicode >> 6 & 0x00ff);
tmp += 1;
*tmp = 0x80 | ( unicode & 0x3f );//0x80 | (unicode & (0xff >> 2));
tmp += 1;
outsize += 3;
}
}
*tmp = '\0';
*out = result;
return 0;
}
//从excel中读取数据
int readExcel(string g_strFileName)
{
_Application l_MyExcelApp;
_Workbook l_MyBook;
Worksheets l_Mysheets;
_Worksheet l_Mysheet;
Workbooks l_MyBooks;
try
{
//读取excel的类
//需要初始化ole
::CoInitialize(0);
if (!l_MyExcelApp.CreateDispatch("Excel.Application",NULL))
{
return(0);
}
l_MyExcelApp.SetDisplayAlerts(false);
l_MyBooks.AttachDispatch(l_MyExcelApp.GetWorkbooks(),TRUE);
LPDISPATCH pBook = l_MyBooks.Open(g_strFileName.c_str(),
vtMissing,vtMissing,vtMissing,vtMissing,vtMissing,vtMissing,
vtMissing,vtMissing,vtMissing,vtMissing,vtMissing,vtMissing);
if (pBook == NULL)
{
return(0);
}
l_MyBook.AttachDispatch(pBook);
l_Mysheets.AttachDispatch(l_MyBook.GetWorksheets(),TRUE);
long SheetCnt = l_Mysheets.GetCount();
for (long iSheet = 0; iSheet < SheetCnt; iSheet++)
{
l_Mysheet.AttachDispatch(l_Mysheets.GetItem(_variant_t(iSheet+1)));
Range usedRange;
usedRange.AttachDispatch(l_Mysheet.GetUsedRange());
Range rangeRow;
rangeRow.AttachDispatch(usedRange.GetRows());
long maxRows = rangeRow.GetCount();
Range rangeCol;
rangeCol.AttachDispatch(usedRange.GetColumns());
long maxCols = rangeCol.GetCount();
//最少一行,最少六列
if(iSheet == 0 && (maxRows < 1 ))
{
break;
}
if (maxCols < 6)
{
continue;
}
//读取数据文件
Range Cells;
Cells.AttachDispatch(l_Mysheet.GetCells());
char strTmp[256] = {0};
for (long iRow = 0; iRow < maxRows; iRow++)
{
for (long iCol=0; iCol<6;iCol++)
{
string strValue("");
Range Cell;
Cell.AttachDispatch(Cells.GetItem (COleVariant((long)iRow+1),COleVariant((long)iCol+1)).pdispVal);
_variant_t vResult;
vResult.lVal = 0;
//此处加false是为了避免内存泄露
vResult=_variant_t(Cell.GetValue(), false);
if(vResult.vt == VT_BSTR) // 字符串
{
strValue = (_bstr_t)vResult.bstrVal;
/*
//从excel中读取的字符是wchar类型的unicode字符,使用GB2312ToUTF_8进行转换
//有问题,不能把韩文等字符转换为UTF8编码,会出现乱码,
//使用unicode_to_utf8来进行转换
uint8_t *utf8 = NULL;
wchar_t WStr[1024];
wcscpy(WStr, (_bstr_t)vResult.bstrVal);
unicode_to_utf8((unsigned short*)WStr, sizeof(WStr), &utf8);
ExcelCell.strSms = (char*)utf8;
free(utf8);
*/
}
//added by Sunday
else if (vResult.vt == VT_DATE) //date
{
DATE dt = vResult.date;
COleDateTime odt = COleDateTime(dt);
CString str;
str = odt.Format( "%Y-%m-%d %H:%M:%S");
strValue = str.GetBuffer();
}
else if (vResult.vt == VT_R8) //int
{
sprintf(strTmp, "%0.f", vResult.dblVal);
strValue = strTmp;
}
//added end
else// 其他
{
strValue="";
}
if (iCol == 0)
{
}
}
}
}
}
catch (CException* e)
{
}
endOfWhile:
l_MyBook.Close(_variant_t(long(FALSE)),vtMissing,vtMissing);
l_Mysheet.ReleaseDispatch();
l_Mysheets.ReleaseDispatch();
l_MyBook.ReleaseDispatch();
l_MyBooks.Close();
l_MyBooks.ReleaseDispatch();
l_MyExcelApp.Quit();
l_MyExcelApp.ReleaseDispatch();
//释放
::CoUninitialize();
return 0;
}
void setExcelTitle(excel::Range& range)
{
int row = 1;
range.SetItem(_variant_t(row),_variant_t((long)1),_variant_t("1"));
range.SetItem(_variant_t(row),_variant_t((long)2),_variant_t("2"));
range.SetItem(_variant_t(row),_variant_t((long)3),_variant_t("3"));
range.SetItem(_variant_t(row),_variant_t((long)4),_variant_t("4"));
range.SetItem(_variant_t(row),_variant_t((long)5),_variant_t("5"));
range.SetItem(_variant_t(row),_variant_t((long)6),_variant_t("6"));
}
int DeleteExcelSheet(CString strSheetName, excel::Worksheets& sheets)
{
int i;
int nNofSheet;
CString strInfo;
excel::_Worksheet sheet;
nNofSheet = sheets.GetCount();
for (i = 1; i <= nNofSheet; i++)
{
// nSheetIndex: base on 1
sheet.AttachDispatch(sheets.GetItem(COleVariant(long(i))));
strInfo = sheet.GetName();
if (strInfo == strSheetName)
{
sheet.Delete();
return TRUE;
}
}
return FALSE;//cannot find the target sheet
}
#define XLS_LEFT (-4131)
#define XLS_MID (-4108)
#define XLS_RIGHT (-4152)
static COleVariant covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
int SetExcelAlignment(int nStartRow, int nStartCol, int nEndRow,int nEndCol,
int nHorizontal /*=XLS_MID*/, excel::_Worksheet& sheet)
{
excel::Range range;
range.AttachDispatch(sheet.GetCells());
excel::Range iCell;
iCell.AttachDispatch(range.GetItem(COleVariant(long(nStartRow)),COleVariant(long(nStartCol))).pdispVal);
iCell.AttachDispatch(iCell.GetResize(COleVariant(long(nEndRow)),COleVariant(long(nEndCol))));
iCell.SetHorizontalAlignment(COleVariant(long(nHorizontal)));
return 1;
}
int SetColumnWidth(excel::_Worksheet& sheet, int nRow, int nCol,long nWidth)
{
excel::Range range;
excel::Range iCell;
range.AttachDispatch(sheet.GetCells());
iCell.AttachDispatch(range.GetItem(COleVariant(long(nRow)),COleVariant(long(nCol))).pdispVal);
iCell.SetColumnWidth(COleVariant(long(nWidth)));
return TRUE;
}
#define MAX_ROW_OF_ONE_EXCELSHEET 200000
long copyFile(const char* from, const char* to)
{
char cmd[1024] = {0};
//sprintf(cmd, "copy %s\\%s %s", g_exePath.c_str(), from, to);
sprintf(cmd, "copy %s %s", from, to);
system(cmd);
cout << "copy done, " << cmd << endl;
return 0;
}
long writeToExcel(const char* fileName)
{
long begin = 1;
long sum = 0;
copyFile(".\\sample.xlsx", fileName);
excel::_Application ExcelApp;
excel::Workbooks wbsMyBooks;
excel::_Workbook wbMyBook;
excel::Worksheets wssMysheets;
excel::_Worksheet wsMysheet;
excel::Range rgMyRge;
if (::CoInitialize( NULL ) == E_INVALIDARG)
{
return -1;
}
try
{
if (!ExcelApp.CreateDispatch((LPCTSTR)"Excel.Application", NULL))
{
return -2;
}
ExcelApp.SetVisible(false); //将excel设置为隐藏状态,防止vc在写入时受到人为干扰
ExcelApp.SetDisplayFullScreen(false);
ExcelApp.SetDisplayAlerts(false);//屏蔽vc关闭excel时跳出的保存对话框
wbsMyBooks.AttachDispatch(ExcelApp.GetWorkbooks(),true);
//fileName = "D:\\09\\10\\test.xlsx";
char path[256] = {0};
strcpy(path, fileName);
wbMyBook.AttachDispatch(wbsMyBooks.Add(_variant_t(path)));//fileName
//得到Worksheets
wssMysheets.AttachDispatch(wbMyBook.GetWorksheets(),true);
//得到sheet1
//wsMysheet.AttachDispatch(wssMysheets.GetItem(_variant_t("Sheet1")),true);
wsMysheet.AttachDispatch(wssMysheets.GetItem(COleVariant(long(1))), true);
wsMysheet.SetVisible(true);
rgMyRge.AttachDispatch(wsMysheet.GetCells(),true);
setExcelTitle(rgMyRge);
//rgMyRge.AutoFit();
CString strSheetName = "Sheet2";
long row = 2;
//rgMyRge.SetItem(_variant_t(row),_variant_t((long)1),_variant_t("tttttttttttttt"));
//loop to write excel file
if (1) //判断文件是否读结束
{
if (1)
{
for (int ic = 0; ic < 9; ic++)
{
sum++;
//rgMyRge.SetItem(_variant_t(row),_variant_t((long)1),_variant_t("tttttttttttttt"));
//write the new sheet
if (sum > 1 && ((sum - 1 ) % MAX_ROW_OF_ONE_EXCELSHEET == 0))
{
char sheetName[256] = {0};
sprintf(sheetName, "第%d条—第%d条", begin, sum - 1);
wsMysheet.SetName(sheetName);
begin += MAX_ROW_OF_ONE_EXCELSHEET;
SetExcelAlignment(2, 1, MAX_ROW_OF_ONE_EXCELSHEET+2, 7, XLS_LEFT, wsMysheet);
SetColumnWidth(wsMysheet, 1, 1, 15);
SetColumnWidth(wsMysheet, 1, 2, 15);
SetColumnWidth(wsMysheet, 1, 3, 15);
SetColumnWidth(wsMysheet, 1, 4, 15);
SetColumnWidth(wsMysheet, 1, 5, 15);
//SetColumnWidth(wsMysheet, 1, 6, 300);
//find the Sheet2, add a new sheet before it
int nNofSheet = wssMysheets.GetCount();
for (int i = 1; i <= nNofSheet; i++)
{
// nSheetIndex: base on 1
wsMysheet.AttachDispatch(wssMysheets.GetItem(COleVariant(long(i))));
CString strInfo = wsMysheet.GetName();
if (strInfo == strSheetName)
{
wsMysheet.Activate();
break;
}
}
//add a sheet
wssMysheets.Add(vtMissing, covOptional, covOptional, covOptional);//add sheet
wsMysheet.AttachDispatch(wbMyBook.GetActiveSheet());
wsMysheet.SetName("sheet1");
rgMyRge.AttachDispatch(wsMysheet.GetCells(),true);
setExcelTitle(rgMyRge);
row = 2;
}
//write data in row, column
rgMyRge.SetItem(_variant_t(row),_variant_t((long)1),_variant_t("str value"));
rgMyRge.SetItem(_variant_t(row),_variant_t((long)2),_variant_t("str value"));
rgMyRge.SetItem(_variant_t(row),_variant_t((long)3),_variant_t("str value"));
rgMyRge.SetItem(_variant_t(row),_variant_t((long)4),_variant_t("str value"));
rgMyRge.SetItem(_variant_t(row),_variant_t((long)5),_variant_t("str value"));
rgMyRge.SetItem(_variant_t(row),_variant_t((long)6),_variant_t("str value"));
row++;
}
}
else
{
}
}
///
char sheetName[256] = {0};
if (sum == 0)
{
begin = 0;
}
sprintf(sheetName, "第%d条—第%d条", begin, sum);
//set the name of the sheet
// wsMysheet.SetName(sheetName);
SetExcelAlignment(2, 1, sum%MAX_ROW_OF_ONE_EXCELSHEET+2, 7, XLS_LEFT, wsMysheet);
SetColumnWidth(wsMysheet, 1, 1, 15);
SetColumnWidth(wsMysheet, 1, 2, 15);
SetColumnWidth(wsMysheet, 1, 3, 15);
SetColumnWidth(wsMysheet, 1, 4, 15);
SetColumnWidth(wsMysheet, 1, 5, 15);
//SetColumnWidth(wsMysheet, 1, 6, 300);
//delete the sheet2 and sheet3
DeleteExcelSheet(strSheetName, wssMysheets);
strSheetName = "Sheet3";
DeleteExcelSheet(strSheetName, wssMysheets);
wsMysheet.SaveAs(path, vtMissing,vtMissing,vtMissing,vtMissing,
vtMissing,vtMissing,vtMissing,vtMissing);//相当于excel菜单的保存 fileName
}
catch (CMemoryException* e)
{
}
catch (COleDispatchException* e)
{
cout << e->m_strDescription << endl;
}
catch (CException* e)
{
}
catch(_com_error &e)
{
cout << (e.Description());
}
catch (...)
{
}
// wbMyBook.SaveCopyAs(_variant_t(strPath)); //相当于excel菜单的另存为
// int ty=MessageBox("关闭EXCEL","", MB_ICONERROR | MB_YESNOCANCEL);
//ExcelApp.SetVisible(true);
//wbMyBook.PrintPreview(_variant_t(false));
//释放对象
rgMyRge.ReleaseDispatch();
wsMysheet.ReleaseDispatch();
wssMysheets.ReleaseDispatch();
wbMyBook.ReleaseDispatch();
wbsMyBooks.ReleaseDispatch();
ExcelApp.Quit();///要想彻底关闭excel进程,必须把ExcelApp.Quit();放在ExcelApp.ReleaseDispatch();之前
ExcelApp.ReleaseDispatch();//
::CoUninitialize();
return 0;
}
int main()
{
cout << "hello " << endl;
// readExcel("D:\\09\\testExcel\\test.xlsx");
//test write
writeToExcel("D:\\09\\testExcel\\write.xlsx");
return 0;
}