#include "stdafx.h"
#include "ToExcel.h"
//#import "C:\Program Files\Common Files\Microsoft Shared\OFFICE14\MSO.DLL"
#import "libid:2DF8D04C-5BFA-101B-BDE5-00AA0044DE52" \
rename("RGB", "MSORGB") \
rename("DocumentProperties", "MSODocumentProperties")
//using namespace Office;
//#import "C:\\Program Files (x86)\\Common Files\\microsoft shared\\VBA\\VBA6\\VBE6EXT.OLB"
#import "libid:0002E157-0000-0000-C000-000000000046"
//using namespace VBIDE;
//#import "C:\\Program Files\\Microsoft Office\\Office14\\EXCEL.EXE"
#import "libid:00020813-0000-0000-C000-000000000046" \
rename("DialogBox", "ExcelDialogBox") \
rename("RGB", "ExcelRGB") \
rename("CopyFile", "ExcelCopyFile") \
rename("ReplaceText", "ExcelReplaceText") \
no_auto_exclude
//using namespace Excel;
BOOL ToExcel(std::vector<SingleRow>& rows, LPCTSTR szExcel)
{
try
{
Excel::_ApplicationPtr app;
app.CreateInstance(_T("Excel.Application"));
ATLASSERT(app);
if (app == NULL)
{
AfxMessageBox(_T("未找到EXCEL软件,请安装EXCEL软件后重试!"));
return FALSE;
}
app->Visible[0] = false;
app->DisplayAlerts[0] = false;
app->AlertBeforeOverwriting[0] = false;
// 读取模板到新的工作簿
TCHAR szMoudlePath[_MAX_PATH] = _T("");
GetModuleFileName( NULL, szMoudlePath, _MAX_PATH );
PathRemoveFileSpec(szMoudlePath);
PathRemoveFileSpec(szMoudlePath);
PathAppend(szMoudlePath, _T("Data\\\zh-CN\\CAXAArcData.xlsx"));
app->Workbooks->Add(szMoudlePath);
//app->Workbooks->Add(Excel::xlWorksheet); //默认方式
Excel::_WorksheetPtr sheet = app->ActiveSheet;
// 将数据写入excel
int n = 2;
for (size_t i = 0; i < rows.size(); ++i)
{
CString szNum, szStartAngle, szEndAngle, szCenterPnt, szRadius;
SingleRow& tempRow = rows[i];
szNum.Format(_T("%d"), n - 1 );
szStartAngle.Format(_T("%.3f"), tempRow.start);
szEndAngle.Format(_T("%.3f"), tempRow.end);
szCenterPnt.Format(_T("(%.3f, %.3f)"), tempRow.centerx, tempRow.centery);
szRadius.Format(_T("%.3f"), tempRow.radius);
sheet->Cells->Item[n][1] = (LPCTSTR)szNum;
sheet->Cells->Item[n][2] = (LPCTSTR)szStartAngle;
sheet->Cells->Item[n][3] = (LPCTSTR)szEndAngle;
sheet->Cells->Item[n][4] = (LPCTSTR)szCenterPnt;
sheet->Cells->Item[n][5] = (LPCTSTR)szRadius;
++n;
}
sheet->SaveAs((LPCTSTR)szExcel);
app->Quit();
}
catch (_com_error& e)
{
CString str = e.Description();
AfxMessageBox(str);
return FALSE;
}
catch(...)
{
AfxMessageBox(_T("有未知异常发生!"));
return FALSE;
}
return TRUE;
}
注意:1. 有时候需要加 AfxOleInit()
2. .h中不需要加stdafx.h , .cpp中需要加,需要放在开头
3. 需要做防御
if (app == NULL)
{
AfxMessageBox(_T(“未找到EXCEL软件,请安装EXCEL软件后重试!”));
return FALSE;
}