Link to home
Start Free TrialLog in
Avatar of RobertParkinson
RobertParkinson

asked on

Excel Sheet Name

Hi,
I need to read the sheet name of an excel file using vc++.
Is this possible?
Thanks
Avatar of mnashadka
mnashadka

There are a whole lot of things that you can do with Excel, but they all require that Excel is installed on the end user's machine.  Look in the .tlh files to start learning.  But either way, here's a way that you can get the name of a worksheet in Excel:

#include <iostream>

// In the #include area,
// import the type library information
#import "C:\Program Files\Microsoft Office\Office\MSO9.DLL" \
  rename("RGB", "OfficeRGB") \
  rename("CopyFile", "OfficeCopyFile") \
  exclude("DocumentProperties") \
  no_namespace

#import "C:\Program Files\Common Files\Microsoft Shared\VBA\VBA6\VBE6EXT.OLB"
#import "C:\Program Files\Microsoft Office\Office\EXCEL9.OLB" \
  rename("DialogBox", "ExcelDialogBox") \
  rename("RGB", "ExcelRGB") \
  rename("CopyFile", "ExcelCopyFile") \
  no_dual_interfaces


// In your function
int main()
{
  CoInitialize(NULL); // Initialize COM
  try
  {
    Excel::_ApplicationPtr excel;
    HRESULT hr = excel.CreateInstance(L"Excel.Application"); // Start excel
    Excel::_WorkbookPtr workbook = excel->Workbooks->Open("c:\\Book1.xls"); // Open the workbook
    Excel::_WorksheetPtr worksheet = workbook->Sheets->Item[1l]; // Get the first worksheet
    std::string worksheet_name = static_cast<char *>(worksheet->Name); // Get the worksheet name
    workbook->Close(); // Close the workbook
    excel->Quit(); // Quit Excel
  }
  catch(_com_error &ce)
  {
    // Error occurred
  }
  CoUninitialize();
  return 0;
}

Good luck!
Avatar of RobertParkinson

ASKER

thanks mnashadka,
I am having a little trouble converting the string worksheet_name into anything that i can use though.
it won't convert to a CString and i can not use it in an AfxMessageBox to test to see if it is working.
any ideas?

Thanks
ASKER CERTIFIED SOLUTION
Avatar of mnashadka
mnashadka

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks mnashadka,
That did the trick!