연습: Visual Studio 프로젝트 자동화를 사용하여 새 Office 프로젝트 만들기

이 연습에서는 Visual Studio 개체 모델을 사용하여 Office 프로젝트 생성을 자동화하는 매크로를 만드는 방법을 보여 줍니다. 이 프로젝트에서는 프로젝트 기본 설정 대신 Visual Studio Tools for Office 프로젝트 마법사를 통한 사용자 지정 설정을 사용합니다.

적용 대상: 이 항목의 정보는 Excel 2010의 문서 수준 프로젝트에 적용됩니다. 자세한 내용은 Office 응용 프로그램 및 프로젝트 형식에 따라 사용 가능한 기능을 참조하십시오.

이 코드에서는 새 통합 문서를 만드는 대신 기존의 Microsoft Office Excel 통합 문서를 사용하여 자동화된 프로젝트를 만들 수 있도록 사용자 지정 마법사 설정으로 새 프로젝트를 만듭니다.

매크로에 대한 자세한 내용은 매크로를 사용하여 반복 작업 자동화를 참조하십시오.

이 연습에서는 다음 작업을 수행합니다.

  • 새 Visual Studio 매크로 만들기

  • 사용자 지정 설정으로 임시 템플릿 파일(.vstemplate) 만들기

  • 마법사의 매개 변수 설정 및 마법사 시작

사전 요구 사항

이 연습을 완료하려면 다음 구성 요소가 필요합니다.

-

Microsoft Office 개발자 도구를 포함하는 Visual Studio 2010 버전입니다. 자세한 내용은 [Office 솔루션을 개발할 수 있도록 컴퓨터 구성](bb398242\(v=vs.100\).md)을 참조하십시오.
  • Excel 2010.

Excel 통합 문서 만들기

새 프로젝트에서 기존 통합 문서로 사용할 Excel 통합 문서를 만들어야 합니다.

Excel 통합 문서를 만들려면

  1. 컴퓨터의 C 드라이브에 CreateNewFile이라는 폴더를 만듭니다.

  2. CreateNewFile에 Test라는 하위 폴더(C:\CreateNewFile\Test)를 만듭니다.

  3. Excel 2010을 엽니다.

  4. A1 셀에 CreateNewFile 통합 문서입니다.를 입력합니다.

  5. 통합 문서를 C:\CreateNewFile 위치에 CreateNewFile.xls로 저장합니다.

  6. Excel을 닫습니다.

Test 하위 폴더는 완성된 프로젝트의 위치로 사용됩니다.

새 매크로 만들기

이 단계에서는 비어 있는 Visual Studio 매크로를 새로 만듭니다.

새 매크로를 만들려면

  1. Visual Studio를 열고 열려 있는 프로젝트를 모두 닫습니다.

  2. 도구 메뉴에서 매크로를 가리킨 다음 매크로 IDE를 클릭합니다.

    Microsoft Visual Studio Macros IDE(통합 개발 환경)가 열립니다.

  3. MyMacros 노드가 확장되어 있지 않으면 이 노드를 확장합니다.

  4. 프로젝트 메뉴에서 모듈 추가를 클릭합니다.

  5. 모듈의 이름을 CreateNewProject로 지정한 다음 추가를 클릭합니다.

새 모듈이 매크로 IDE에 열립니다. 이제 새 프로젝트를 만들기 위한 코드를 추가할 수 있습니다.

템플릿 파일(.vstemplate) 만들기

기본 마법사 설정을 사용하여 새 프로젝트를 만들려면 미리 정의된 템플릿 파일 중 하나를 사용합니다. Visual Studio의 경우 프로젝트에 사용할 새 문서나 통합 문서를 만들도록 기본 설정되어 있습니다. 프로젝트에 기존의 통합 문서를 사용하려면 올바르게 설정된 사용자 지정 임시 .vstemplate 파일을 생성해야 합니다.

.vstemplate 파일에 대한 자세한 내용은 Visual Studio 템플릿을 참조하십시오.

기존 문서를 사용하려면 사용자 지정 매개 변수 VSTOExistingDocumentPath를 .vstemplate 파일에 추가합니다.

임시 .vsz 파일을 생성하려면

  1. 프로젝트 메뉴에서 참조 추가를 클릭합니다.

  2. System.Xml.dll을 선택하고 추가를 클릭한 다음 확인을 클릭합니다.

  3. 코드 파일의 맨 위에 다음 가져오기 문을 추가합니다.

    Imports System.Xml
    Imports System.IO
    
  4. CreateNewProject 모듈에서 다음 메서드를 추가하여 임시 템플릿 폴더의 내용을 정의합니다.

    Sub CreateVstemplateFile(ByVal defaultTemplateFilePath As String, _
        ByVal templateFilePath As String, ByVal docFilePath As String)
    
        ' Copy the default template in the temporary location.
        Dim defaultTemplateDirectory = _
            Path.GetDirectoryName(defaultTemplateFilePath)
        Dim templateDirectory = Path.GetDirectoryName(templateFilePath)
        If Not Directory.Exists(templateDirectory) Then
            Directory.CreateDirectory(templateDirectory)
        End If
        For Each fileToCopy As String In Directory. _
            GetFiles(defaultTemplateDirectory)
            File.Copy(fileToCopy, Path.Combine(templateDirectory, _
                Path.GetFileName(fileToCopy)), True)
        Next
    
        ' Create the vstemplate namespace.
        Dim vstemplateNamespace As String = _
            "https://schemas.microsoft.com/developer/vstemplate/2005"
    
        ' Load the XML document.
        Dim doc As XmlDocument = New XmlDocument()
        doc.Load(templateFilePath)
        Dim xmlNsManager As XmlNamespaceManager = _
            New XmlNamespaceManager(doc.NameTable)
        xmlNsManager.AddNamespace("vstemplns", vstemplateNamespace)
    
        ' Get 'CustomParameters' XML node.
        Dim customParametersNode As XmlNode = doc.SelectSingleNode( _
            "/vstemplns:VSTemplate/vstemplns:TemplateContent/" _
            & "vstemplns:CustomParameters", xmlNsManager)
    
        ' Create a new XML CustomParameter node with 
        ' the existing document data.
        ' <CustomParameter Name="VSTOExistingDocumentPath" _
        ' Value="C:\CreateNewFile\CreateNewFile.xls" />
        Dim newNode As XmlNode
        newNode = doc.CreateElement("CustomParameter", _
            vstemplateNamespace)
        Dim nameAttribute As XmlAttribute
        nameAttribute = doc.CreateAttribute("Name")
        Dim valueAttribute As XmlAttribute
        valueAttribute = doc.CreateAttribute("Value")
    
        nameAttribute.Value = "VSTOExistingDocumentPath"
        valueAttribute.Value = docFilePath
    
        newNode.Attributes.Append(nameAttribute)
        newNode.Attributes.Append(valueAttribute)
    
        customParametersNode.AppendChild(newNode)
        doc.Save(templateFilePath)
    End Sub
    

다음 메서드에서는 매개 변수를 정의하고 LaunchWizard 메서드를 호출합니다.

마법사 시작

새 프로젝트를 만들려면 DTE 개체의 LaunchWizard 메서드를 사용합니다.

마법사를 시작하려면

  • 다음 메서드를 CreateNewProject 모듈에 추가하여 매개 변수 배열을 채우고 마법사를 시작합니다.

    Sub LaunchWizard(ByVal projectName As String, _
        ByVal projectFolder As String, _
        ByVal templateFilePath As String)
    
        Dim params(6) As Object
    
        ' New project.
        params(0) = "{0F90E1D0-4999-11D1-B6D1-00A0C90F2744}"
    
        ' Project name.
        params(1) = projectName
    
        ' Project location.
        params(2) = projectFolder
    
        ' Install location.
        params(3) = ""
    
        ' Close solution.
        params(4) = False
    
        ' Solution name.
        params(5) = ""
    
        ' Silent - do not display any user interface.
        params(6) = False
    
        DTE.LaunchWizard(templateFilePath, params)
    End Sub
    

마지막으로 방금 만든 두 메서드를 호출하는 메서드를 추가하고 적절한 매개 변수를 전달합니다.

프로젝트 만들기

다음 메서드에서는 CreateVstemplateFile 및 LaunchWizard 메서드에 대한 올바른 매개 변수를 정의하고 전달합니다.

프로젝트를 만들려면

  1. 다음 메서드를 CreateNewProject 모듈에 추가합니다.

    Sub CreateProject()
        Dim sol As Solution2 = DTE.Solution
    
        ' Get the path of the default .vstemplate file using 
        ' the name of the template zip file and the language.
        ' The zip files are "VSTOExcelWorkbook.zip", 
        ' "VSTOExcelTemplate.zip", ' "VSTOWordDocument.zip", 
        ' or "VSTOWordTemplate.zip".
        ' The languages are "VisualBasic" and "CSharp".
        Dim defaultTemplateFilePath As String = _
            sol.GetProjectTemplate("VSTOExcel2010WorkbookV4.zip", _
            "VisualBasic")
    
        ' Get the temporary .vstemplate file containing 
        ' the specification.
        Dim templateDirectory As String = "C:\CreateNewFile\template"
        Dim templateFilePath = Path.Combine(templateDirectory, _
            Path.GetFileName(defaultTemplateFilePath))
    
        ' Get an existing document to use in project creation.
        Dim docFilePath As String = "C:\CreateNewFile\CreateNewFile.xls"
    
        ' Create a temporary template with the wizard specification.
        CreateVstemplateFile(defaultTemplateFilePath, _
            templateFilePath, docFilePath)
    
        ' Launch the CreateProject wizard.
        Dim projectName As String = "CreateNewFile"
        Dim projectFolder As String = "c:\CreateNewFile\test"
        LaunchWizard(projectName, projectFolder, templateFilePath)
    End Sub
    
  2. 매크로를 저장합니다.

  3. 매크로 IDE를 닫습니다.

매크로 테스트

이제 매크로를 테스트하여 새 프로젝트가 작성되는지 확인합니다.

매크로를 테스트하려면

  1. 도구 메뉴에서 매크로를 가리킨 다음 매크로 탐색기를 클릭합니다.

  2. 매크로 탐색기에서 MyMacros 아래에 있는 CreateNewProject 매크로를 확장합니다.

  3. CreateNewProject 아래에서 CreateProject를 두 번 클릭합니다.

    Visual Studio Tools for Office 프로젝트 마법사가 열립니다.

  4. 응용 프로그램에 사용할 문서 선택 페이지에서 확인을 클릭합니다.

  5. Test 하위 폴더에 새 프로젝트가 생성되는지 확인합니다.

참고 항목

작업

방법: Visual Studio 프로젝트 자동화를 사용하여 통합 문서에 워크시트 추가

방법: Visual Studio 프로젝트 자동화를 사용하여 Excel 속성 변경

개념

Visual Basic 및 Visual C# 프로젝트 확장성 예제

기타 리소스

Office 프로젝트의 확장성