MFC와 Visual C++ 2005 또는 Visual C++ .NET을 사용하여 Excel 워크시트를 포함하고 자동화하는 방법
이 문서가 적용되는 제품 보기.
기술 자료 ID : 311546
마지막 검토 : 2006년 4월 21일 금요일
수정 : 5.0
이 문서는 이전에 다음 ID로 출판되었음: KR311546
이 문서의 Microsoft Visual C++ 6.0 버전에 대한 내용은 184663 (http://support.microsoft.com/kb/184663/)을 참조하십시오.

참고 Microsoft Visual C++ 2005, Microsoft Visual C++ .NET 2003 및 Microsoft Visual C++ .NET 2002에서는 Microsoft .NET Framework에서 제공하는 관리 코드 모델과 기본 Microsoft Windows의 비관리 코드 모델을 모두 지원합니다. 이 문서에 나와 있는 정보는 Visual C++의 비관리 코드에만 적용됩니다.
이 페이지에서

요약

Excel 워크시트를 포함시키는 MFC 응용 프로그램 만들기

응용 프로그램 테스트

문제 해결

참조
요약
이 문서에서는 Visual C++ 2005나 Visual C++ .NET을 사용하여 SDI(단일 문서 인터페이스) Microsoft Foundation Classes(MFC) 응용 프로그램의 View 개체에 Excel 워크시트를 포함시키는 방법을 단계별로 설명합니다.
위로 가기

Excel 워크시트를 포함시키는 MFC 응용 프로그램 만들기
다음 단계에서는 워크시트를 포함시키고, 셀에 데이터를 추가하도록 워크시트를 자동화하는 방법을 설명합니다. 1. Microsoft Visual Studio .NET을 시작합니다. 파일 메뉴에서 새로 만들기를 누른 다음 프로젝트를 누릅니다. 프로젝트 형식에서 Visual C++ 프로젝트를 누른 다음 템플릿에서 MFC 응용 프로그램을 누릅니다. 프로젝트 이름을 Embed_Excel로 지정합니다.

참고 Visual C++ 2005에서 Visual C++ 프로젝트 대신 Visual C++를 누릅니다.
2. MFC 응용 프로그램 마법사가 나타나면 다음 단계를 수행합니다. a. 응용 프로그램 종류를 누른 다음 단일 문서를 선택합니다.
b. 복합 문서 지원을 누른 다음 컨테이너를 선택합니다.
c. 마침을 눌러 다른 기본 설정을 모두 그대로 적용합니다.

3. Excel 개체 라이브러리의 인터페이스를 추가합니다. 이렇게 하려면 다음 단계를 수행하십시오. a. 프로젝트 메뉴에서 클래스 추가를 누릅니다.
b. 템플릿 목록에서 MFC Class From TypeLib를 선택한 다음 열기를 누릅니다. TypeLib의 클래스 추가 마법사가 나타납니다.

참고 Visual C++ 2005에서는 열기 대신 추가를 누릅니다.
c. 사용 가능한 형식 라이브러리 목록에서 Microsoft Excel version 개체 라이브러리를 찾습니다. version은 Excel 2000의 경우 9.0이고 Excel 2002의 경우 10.0이며 Microsoft Office Excel 2003의 경우 11.0입니다.
d. 다음 인터페이스를 추가합니다. ? _Application
? _Workbook
? _Worksheet
? Range
? Workbooks
? Worksheets

e. 마침을 누릅니다.

4. Cntritem.h에 CEmbed_ExcelCntrItem 클래스의 공용 멤버 함수로 다음 행을 추가합니다.LPDISPATCH GetIDispatch();

5. 다음과 같이 Cntritem.cpp에 GetIDispatch 메서드를 추가합니다./*******************************************************************
* This method returns the IDispatch* for the application linked to
* this container.
********************************************************************/
LPDISPATCH CEmbed_ExcelCntrItem::GetIDispatch()
{
//The this and m_lpObject pointers must be valid for this function
//to work correctly. The m_lpObject is the IUnknown pointer to
// this object.
ASSERT_VALID(this);

ASSERT(m_lpObject != NULL);

LPUNKNOWN lpUnk = m_lpObject;

//The embedded application must be running in order for the rest
//of the function to work.
Run();

//QI for the IOleLink interface of m_lpObject.
LPOLELINK lpOleLink = NULL;
if (m_lpObject->QueryInterface(IID_IOleLink,
(LPVOID FAR*)&lpOleLink) == NOERROR)
{
ASSERT(lpOleLink != NULL);
lpUnk = NULL;

//Retrieve the IUnknown interface to the linked application.
if (lpOleLink->GetBoundSource(&lpUnk) != NOERROR)
{
TRACE0("Warning: Link is not connected!
");
lpOleLink->Release();
return NULL;
}
ASSERT(lpUnk != NULL);
}

//QI for the IDispatch interface of the linked application.
LPDISPATCH lpDispatch = NULL;
if (lpUnk->QueryInterface(IID_IDispatch, (LPVOID FAR*)&lpDispatch)
!=NOERROR)
{
TRACE0("Warning: does not support IDispatch!
");
return NULL;
}

//After you verify that it is valid, return the IDispatch
//interface to the caller.
ASSERT(lpDispatch != NULL);
return lpDispatch;
}

참고 Visual C++ 2005에서는 공용 언어 런타임 지원 컴파일러 옵션(/clr:oldSyntax)을 추가해야 이전 코드 예제를 성공적으로 컴파일할 수 있습니다. 공용 언어 런타임 지원 컴파일러 옵션을 추가하려면 다음과 같이 하십시오. 1. 프로젝트를 누르고 ProjectName 속성을 누릅니다.

참고 ProjectName은 프로젝트 이름의 자리 표시자입니다.
2. 구성 속성을 확장하고 일반을 누릅니다.
3. 오른쪽 창의 공용 언어 런타임 지원 프로젝트 설정에서 공용 언어 런타임 지원, 이전 구문(/clr:oldSyntax)을 선택합니다.
4. 적용을 누른 다음 확인을 누릅니다.
공용 언어 런타임 지원 컴파일러 옵션에 대한 자세한 내용은 다음 MSDN(Microsoft Developer Network) 웹 사이트를 참조하십시오.
http://msdn.microsoft.com/library/kor/default.asp?url=/library/kor/vccore/html/vcrefeecomcompilation.asp (http://msdn.microsoft.com/library/kor/default.asp?url=/library/kor/vccore/html/vcrefeecomcompilation.asp)
위의 단계는 문서 전체에 적용됩니다.
6. Embed_excelview.h에 CEmbed_ExcelView 클래스의 공용 메서드로 다음 행을 추가합니다.void EmbedAutomateExcel();


7. Embed_excelview.cpp에 다음 행을 추가합니다.#include "CApplication.h"
#include "CWorkbook.h"
#include "CWorksheet.h"
#include "CRange.h"
#include "CWorksheets.h"
#include "CWorkbooks.h"

/********************************************************************
* This method encapsulates the process of embedding an Excel
* Worksheet in a View object and automating that worksheet to add
* some text to cell A1.
********************************************************************/
void CEmbed_ExcelView::EmbedAutomateExcel()
{
//Change the cursor so that the user knows that something exciting is going
//on.
BeginWaitCursor();

CEmbed_ExcelCntrItem* pItem = NULL;
TRY
{
//Get the document associated with this view, and be sure that it is
//valid.
CEmbed_ExcelDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);

//Create a new item associated with this document, and be sure that
//it is valid.
pItem = new CEmbed_ExcelCntrItem(pDoc);
ASSERT_VALID(pItem);

// Get a Class ID for the Excel sheet.
// This is used in creation.
CLSID clsid;
if(FAILED(::CLSIDFromProgID(L"Excel.sheet",&clsid)))
//Any exception will do. You just need to break out of the
//TRY statement.
AfxThrowMemoryException();

// Create the Excel embedded item.
if(!pItem->CreateNewItem(clsid))
//Any exception will do. You just need to break out of the
//TRY statement.
AfxThrowMemoryException();

//Make sure the new CContainerItem is valid.
ASSERT_VALID(pItem);

// Start the server to edit the item.
pItem->DoVerb(OLEIVERB_SHOW, this);

// As an arbitrary user interface design, this sets the
// selection to the last item inserted.
m_pSelection = pItem; // Set selection to last inserted. item
pDoc->UpdateAllViews(NULL);

//Query for the dispatch pointer for the embedded object. In
//this case, this is the Excel worksheet.
LPDISPATCH lpDisp;
lpDisp = pItem->GetIDispatch();

//Add text in cell A1 of the embedded Excel sheet.
CWorkbook wb;
CWorksheets wsSet;
CWorksheet ws;
CRange CRange;
CApplication app;

//Set CWorkbook wb to use lpDisp, the IDispatch* of the
//actual workbook.
wb.AttachDispatch(lpDisp);

//Get the application for the worksheet.
app = wb.get_Application();

//Get the first worksheet in the workbook.
wsSet = wb.get_Worksheets();
ws = wsSet.get_Item(COleVariant((short)1));

//Get a CRange object that corresponds to cell A1.
CRange = ws.get_Range(COleVariant("A1"), COleVariant("A1"));

//Fill A1 with the string "Hello, World!"
CRange.put_Value2(COleVariant("Hello, World!"));

//NOTE: If you are automating Excel 2002, the CRange.SetValue method has an
//additional optional parameter that specifies the data type. Because the
//parameter is optional, existing code will still work correctly, but new
//code should use the new convention. The call for Excel2002 should
//resemble the following:

//CRange.SetValue( ColeVariant( (long)DISP_E_PARAMNOTFOUND, VT_ERROR ),
// COleVariant("Hello, World!"));
}

//Clean up if something went wrong.
CATCH(CException, e)
{
if (pItem != NULL)
{
ASSERT_VALID(pItem);
pItem->Delete();

}
AfxMessageBox(IDP_FAILED_TO_CREATE);
}
END_CATCH

//Set the cursor back to normal so that the user knows that exciting stuff
//is no longer happening.
EndWaitCursor();
}


8. Embed_excelview.cpp에서 CEmbed_ExcelView::OnInsertObject에 대한 코드를 다음 코드로 바꿉니다. void CEmbed_ExcelView::OnInsertObject()
{
EmbedAutomateExcel();
}

참고: EmbedAutomateExcel은 단지 OnInsertObject의 특별한 경우로, 이를 사용하면 사용자가 사용 가능한 OLE 개체 목록에서 선택하여 응용 프로그램에 삽입할 수 있습니다. 이 예제에는 필요하지 않으므로 이 동작을 무시합니다.

위로 가기

응용 프로그램 테스트
1. F5 키를 눌러 응용 프로그램을 빌드하고 실행합니다.
2. 응용 프로그램의 Edit 메뉴에서 Insert New Object를 누릅니다.
3. 결과를 검사합니다. 셀 A1에 "Hello, World!"라는 텍스트가 나타나 있는 새로운 Excel 워크시트가 View 개체에 포함됩니다.

위로 가기

문제 해결
? TypeLib의 클래스 추가 마법사의 파일 옵션을 사용하여 Excel 개체 라이브러리의 클래스 래퍼를 추가한 경우 해당 개체 라이브러리를 탐색하면 오류 메시지가 나타날 수 있습니다. 이 문제를 방지하려면 파일을 탐색하는 대신 개체 라이브러리의 전체 경로와 파일 이름을 입력합니다.자세한 내용은 Microsoft 기술 자료의 다음 문서를 참조하십시오.
311408 (http://support.microsoft.com/kb/311408/) FIX: 형식 라이브러리의 MFC 클래스를 추가할 때 'Read-Only' 경고가 나타난다
? 예제 응용 프로그램을 빌드할 때 다음과 같은 오류 메시지가 나타나면 CRange.h의 "Variant DialogBox"를 "Variant _DialogBox"로 변경하십시오.
경고 C4003: 'DialogBoxA' 매크로의 실제 매개 변수가 부족합니다.
이 오류의 원인에 대한 자세한 내용은 Microsoft 기술 자료의 다음 문서를 참조하십시오.
311407 (http://support.microsoft.com/kb/311407/) BUG: MFC 클래스 마법사가 Windows API와 COM 인터페이스 메서드 간의 이름 충돌을 해결하지 않는다

위로 가기

참조
자세한 내용은 다음 MSDN(Microsoft Developer Network) 웹 사이트를 참조하십시오.
Visual Studio를 사용한 Microsoft Office 개발
http://msdn.microsoft.com/library/en-us/dnoxpta/html/vsofficedev.asp (http://msdn.microsoft.com/library/en-us/dnoxpta/html/vsofficedev.asp)(영문)
Excel 자동화에 대한 자세한 내용은 Microsoft 기술 자료의 다음 문서를 참조하십시오.
308407 (http://support.microsoft.com/kb/308407/) Visual C++ 2005 또는 Visual C++ .NET 및 MFC를 통해 배열을 사용하여 일정 범위의 데이터를 채우거나 가져오도록 Excel을 자동화하는 방법
308292 (http://support.microsoft.com/kb/308292/) C++ .NET 및 MFC를 사용하여 새 통합 문서를 만들고 서식을 지정하도록 Excel을 자동화하는 방법

Posted by nurgoori

2006/06/08 00:49 2006/06/08 00:49
, ,
Response
No Trackback , No Comment
RSS :
http://www.nurgoori.com/rss/response/85


블로그 이미지

방랑하는 너구리의 이야기가 있는 곳입니다.

- nurgoori

Archives

Authors

  1. nurgoori

Calendar

«   2010/09   »
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30    

Site Stats

Total hits:
154903
Today:
19
Yesterday:
44