ASP의 DataGrid에서 데이터를 내보내는 방법. NET WebForm에서 Microsoft Excel로

요약

이 단계별 가이드를 사용하여 ASP.NET WebForm에서 DataGrid 웹 서버 컨트롤을 채우고 DataGrid의 내용을 Microsoft Excel로 내보냅니다.

기술을

이 문서에서는 DataGrid에서 데이터를 내보내는 두 가지 기술에 대해 설명합니다.

  • Excel MIME 형식 사용(또는 콘텐츠 형식)

    서버 쪽 코드를 사용하면 DataGrid를 데이터에 바인딩하고 데이터를 클라이언트 컴퓨터의 Excel에서 열 수 있습니다. 이렇게 하려면 ContentType을 application/vnd.ms-excel로 설정합니다. 클라이언트가 새 스트림을 받으면 웹 브라우저에서 콘텐츠가 새 페이지로 열린 것처럼 데이터가 Excel에 표시됩니다.

  • Excel Automation 사용

    클라이언트 쪽 코드를 사용하면 DataGrid에서 HTML을 추출한 다음 Excel을 자동화하여 새 통합 문서에 HTML을 표시할 수 있습니다. Excel Automation을 사용하면 데이터가 항상 Excel 응용 프로그램 창의 브라우저 외부에 표시됩니다. Automation의 장점 중 하나는 데이터를 내보낸 후 통합 문서를 수정하려는 경우 프로그래밍 방식으로 Excel을 제어할 수 있다는 것입니다. 그러나 Excel은 스크립팅에 안전한 것으로 표시되지 않으므로 클라이언트는 웹 브라우저에서 Automation을 허용하는 보안 설정을 적용해야 합니다.

단계별

  1. Visual Studio .NET을 시작합니다. 파일 메뉴에서 새로 만들기를 가리킨 다음 프로젝트를 클릭합니다.

  2. 프로젝트 형식 창에서 Visual Basic 프로젝트를 클릭합니다. 템플릿에서 ASP.NET 웹 애플리케이션을 클릭합니다. 응용 프로그램 이름을 ExcelExport로 지정한 다음 확인을 클릭합니다.

    WebForm1이 디자인 보기에 표시됩니다.

  3. 솔루션 탐색기 WebForm1.aspx를 마우스 오른쪽 단추로 클릭한 다음 이름 바꾸기를 클릭합니다. 파일 이름을 Bottom.aspx로 변경합니다.

  4. 보기 메뉴에서 HTML 원본을 클릭하여 다음 DataGrid를

    태그:

    <asp:datagrid id="DataGrid1" runat="server" GridLines="Vertical" CellPadding="3" BackColor="White"
    BorderColor="#999999" BorderWidth="1px" BorderStyle="None" Width="100%" Height="100%" Font-Size="X-Small"
    Font-Names="Verdana">
    <SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#008A8C"></SelectedItemStyle>
    <AlternatingItemStyle BackColor="Gainsboro"></AlternatingItemStyle>
    <ItemStyle BorderWidth="2px" ForeColor="Black" BorderStyle="Solid" BorderColor="Black" BackColor="#EEEEEE"></ItemStyle>
    <HeaderStyle Font-Bold="True" HorizontalAlign="Center" BorderWidth="2px" ForeColor="White" BorderStyle="Solid"
    BorderColor="Black" BackColor="#000084"></HeaderStyle>
    <FooterStyle ForeColor="Black" BackColor="#CCCCCC"></FooterStyle>
    <PagerStyle HorizontalAlign="Center" ForeColor="Black" BackColor="#999999" Mode="NumericPages"></PagerStyle>
    </asp:datagrid>
    
    
  5. 보기 메뉴에서 디자인을 클릭하여 디자인 보기로 돌아갑니다.

    DataGrid가 WebForm에 나타납니다.

  6. 보기 메뉴에서 코드를 클릭하여 웹 양식 뒤에 코드를 표시합니다. Page_Load 이벤트 처리기에 다음 코드를 추가합니다.

    참고 이 코드를 실행하기 전에 사용자 ID <사용자> 이름 및 password=<strong 암호를> 올바른 값으로 변경해야 합니다. 사용자 계정에 데이터베이스에서 이 작업을 수행할 수 있는 올바른 권한이 있는지 확인합니다.

    ' Create a connection and open it.
    Dim objConn As New System.Data.SqlClient.SqlConnection("User ID=<username>;Password=<strong password>;Initial Catalog=Northwind;Data Source=SQLServer;")
    objConn.Open()
    
    Dim strSQL As String
    Dim objDataset As New DataSet()
    Dim objAdapter As New System.Data.SqlClient.SqlDataAdapter()
    
    ' Get all the customers from the USA.
    strSQL = "Select * from customers where country='USA'"
    objAdapter.SelectCommand = New System.Data.SqlClient.SqlCommand(strSQL, objConn)
    ' Fill the dataset.
    objAdapter.Fill(objDataset)
    ' Create a new view.
    Dim oView As New DataView(objDataset.Tables(0))
    ' Set up the data grid and bind the data.
    DataGrid1.DataSource = oView
    DataGrid1.DataBind()
    
    ' Verify if the page is to be displayed in Excel.
    If Request.QueryString("bExcel") = "1" Then
        ' Set the content type to Excel.
        Response.ContentType = "application/vnd.ms-excel"
        ' Remove the charset from the Content-Type header.
        Response.Charset = ""
        ' Turn off the view state.
        Me.EnableViewState = False
    
    Dim tw As New System.IO.StringWriter()
        Dim hw As New System.Web.UI.HtmlTextWriter(tw)
    
    ' Get the HTML for the control.
        DataGrid1.RenderControl(hw)
        ' Write the HTML back to the browser.
        Response.Write(tw.ToString())
        ' End the response.
        Response.End()
    End If
    
    

    참고 코드의 SQLServer를 SQL Server 이름으로 바꿉 있습니다. Northwind 샘플 데이터베이스가 포함된 SQL Server 액세스할 수 없는 경우 Microsoft Access 2002 샘플 Northwind 데이터베이스를 사용하도록 연결 문자열을 수정합니다.

    provider=microsoft.jet.oledb.4.0; data source=C:\Program Files\Microsoft Office\Office10\Samples\Northwind.mdb

    이 메서드를 선택하는 경우 앞서 언급한 코드를 수정하여 SqlClient 네임스페이스가 아닌 OleDbClient 네임스페이스를 사용합니다.

  7. 프로젝트 메뉴에서 HTML 페이지 추가를 클릭합니다. 페이지 이름을 Top.htm 다음 열기를 클릭합니다.

    Top.htm 디자인 보기에 나타납니다.

  8. 보기 메뉴에서 HTML 원본을 클릭합니다. HTML 원본 창의 내용을 다음 코드로 바꿉니다.

    <html>
    <script language="vbscript">
      Sub Button1_onclick        
    
    Select Case Select1.selectedIndex
    
    Case 0' Use Automation.
          Dim sHTML
          sHTML = window.parent.frames("bottom").document.forms(0).children("DataGrid1").outerhtml
          Dim oXL, oBook
          Set oXL = CreateObject("Excel.Application")
          Set oBook = oXL.Workbooks.Add
          oBook.HTMLProject.HTMLProjectItems("Sheet1").Text = sHTML
          oBook.HTMLProject.RefreshDocument
          oXL.Visible = true
          oXL.UserControl = true
    
    Case 1' Use MIME Type (In a New Window).
          window.open("bottom.aspx?bExcel=1")
    
    Case 2' Use MIME Type (In the Frame).
          window.parent.frames("bottom").navigate "bottom.aspx?bExcel=1"
      End Select
    End Sub
    </script>
    <body>
    Export to Excel Using:
    <SELECT id="Select1" size="1" name="Select1">
    <OPTION value="0" selected>Automation</OPTION>
    <OPTION value="1">MIME Type (In a New Window)</OPTION>
    <OPTION value="2">MIME Type (In the Frame)</OPTION>
    </SELECT>
    <INPUT id="Button1" type="button" value="Go!" name="Button1">
    </body>
    </html>
    
    
  9. 프로젝트 메뉴에서 HTML 페이지 추가를 클릭합니다. 페이지 이름을 Frameset.htm 다음 열기를 클릭합니다.

    Frameset.htm 디자인 보기에서 열립니다.

  10. 보기 메뉴에서 HTML 원본을 클릭합니다. HTML 원본 창의 내용을 다음 코드로 바꿉니다.

    <html>
    <frameset rows="10%,90%">
    <frame noresize="0" scrolling="no" name="top" src="top.htm">
    <frame noresize="0" scrolling="yes" name="bottom" src="bottom.aspx">
    </frameset>
    </html>
    
    
  11. 솔루션 탐색기 Frameset.htm 마우스 오른쪽 단추로 클릭한 다음 [시작 페이지로 설정]을 클릭합니다.

  12. 빌드 메뉴에서 솔루션 빌드를 클릭합니다.

사용해 보세요!

  1. 디버그 메뉴에서 디버깅하지 않고 시작을 클릭하여 애플리케이션을 실행합니다.

    웹 브라우저에서 프레임 세트가 열리면 아래쪽 프레임의 DataGrid에 Northwind 데이터베이스의 데이터가 표시됩니다.

  2. 드롭다운 목록에서 Automation을 클릭한 다음 이동을 클릭합니다.

    DataGrid 콘텐츠는 Microsoft Excel 응용 프로그램 창의 브라우저 외부에 표시됩니다.

  3. 드롭다운 목록에서 MIME 유형(새 창에서)을 클릭한 다음 이동을 클릭합니다.

    DataGrid 콘텐츠는 새 웹 브라우저 창에서 호스트되는 Excel에 표시됩니다.

    참고 Excel 파일을 열거나 저장하라는 메시지가 표시되면 열기를 클릭합니다.

  4. 드롭다운 목록에서 MIME 유형(프레임 내) 을 클릭한 다음 이동을 클릭합니다.

    DataGrid 콘텐츠는 웹 브라우저에서 호스트되는 Excel에서 프레임 세트의 아래쪽 프레임에 표시됩니다.

    참고 Excel 파일을 열거나 저장하라는 메시지가 표시되면 열기를 클릭합니다.

참조

자세한 내용은 Microsoft 기술 자료의 문서를 참조하세요.

296717 PRB: Internet Explorer에서 사용자에게 ASP에서 스트리밍된 Office 파일을 열거나 저장하라는 메시지를 표시합니다.