我正在实现Excel C ++ Communicator API,用于将图形图表导出到图像文件。
以下是C ++代码。
// Launch Excel
Excel::_ApplicationPtr spXlApp;
HRESULT hr = spXlApp.CreateInstance(__uuidof(Excel::Application));
// Open sheet
Excel::WorkbooksPtr spXlBooks = spXlApp->Workbooks;
Excel::_WorkbookPtr spXlBook = spXlBooks->Open(L"D:\\Sample1.xlsx");
Excel::_WorksheetPtr spXlSheet = spXlBook->Worksheets->Item[1];
// Get chart
Excel::ChartObjectPtr spXlChartObj = spXlSheet->ChartObjects(1);
Excel::_ChartPtr spXlChart = spXlChartObj->Chart;
// Everything is fine here.
// All pointers are valid (especially spXlChart)
// and I do have the right chart selected.
// Do things with Chart
wprintf(L"%s\n", spXlChart->Name);
spXlChart->Export(L"D:\\Chart.png");
spXlChart->名称和 spXlChart->导出会导致访问冲突。调试器停在以下代码的get_Name行:
#pragma implementation_key(16574)
inline _bstr_t Excel::_Chart::GetName ( ) {
BSTR _result = 0;
HRESULT _hr = get_Name(&_result);
if (FAILED(_hr)) _com_issue_errorex(_hr, this, __uuidof(this));
return _bstr_t(_result, false);
}
我尝试使用Tcom Excel完全相同的操作,一切正常。
有人能给我一些帮助吗?谢谢
答案 0 :(得分:0)
发现问题:#import语句未引用正确的Office版本。
我的程序基于CppAutomateExcel samples,提供了2个Excel自动化解决方案:#import和COM API。
我选择了为Office 12编写的#import,而我安装了Office 15。这可能是某些命令不起作用的原因。
然后我采用了COM API解决方案,它似乎与版本无关。现在一切都很好。
感谢@Hans Passant的评论。
答案 1 :(得分:0)
尝试这个。
Excel::_ChartPtr spXlChart = (IUnknown*)spXlChartObj->Chart;
这是#import bug。