logo
border border
              
border border
border border
  Post Subject :: #75. ASP.NET을 이용한 Excel 파일 읽어오기     [ASP.NET]
border border
border border
     
프로젝트를 수행하면서, Excel 파일에 있는 정보를 가져와야 할 필요가 생겼습니다. 단순하게 Excel 파일을 가져오는 것에 대한 정보는 많았지만 Microsoft Office 2007로 저장된 확장자 "xlsx"에 관련된 처리를 하는 정보는 없었습니다. 많은 시간의 검색 끝에 결국 확장자가 "xlsx"인 엑셀 파일의 정보를 가져오는 방법을 알게 되었습니다.

우선, <그림 1>과 같은 엑셀 파일을 만들고 확장자 "xls"와 확장자 "xlsx"로 각각 저장합니다.


<그림 1> Excel 파일의 내용

다음으로는 Excel 파일을 읽어올 웹 페이지의 코드를 작성합니다. 먼저 웹 폼 페이지의 소스 코드입니다.

<form id="form1" runat="server">

    <div class="content">

        <div>

            <h3>엑셀 파일 업로드 : <asp:Label ID="lblUploadText" runat="server"></asp:Label></h3><br />

        </div>           

        <div>

            XLS 파일 : <asp:FileUpload ID="FileUpload1" runat="server" CssClass="txtCommon" Width="300" />&nbsp;

            <asp:Button ID="ButtonUpload1" runat="server" Text="업로드" Width="100" CssClass="txtCommon" OnClick="ButtonUpload1_Click" /><br />

            XLSX 파일 : <asp:FileUpload ID="FileUpload2" runat="server" CssClass="txtCommon" Width="300" />&nbsp;

            <asp:Button ID="ButtonUpload2" runat="server" Text="업로드" Width="100" CssClass="txtCommon" OnClick="ButtonUpload2_Click" /><br /><br />

 

        </div>

        <div><hr /></div>

        <div>

            <asp:GridView ID="GridView1" runat="server" BackColor="White"

                BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3"

                ForeColor="Black" GridLines="Vertical" Width="719px">

                <FooterStyle BackColor="#CCCCCC" />

                <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />

                <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />

                <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />

                <AlternatingRowStyle BackColor="#CCCCCC" />

            </asp:GridView>

        </div>

    </div>

</form>


업로드 역할과 업로드한 엑셀 파일의 정보를 읽어오는 코드가 담겨있는 비하인드 파일의 코드는 다음과 같습니다.

using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Data.OleDb;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

 

public partial class UseExcel : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

 

    protected void ButtonUpload1_Click(object sender, EventArgs e)

    {

        string strFilePath = string.Empty;

        string strFileType = string.Empty;

        string strFileName = string.Empty;

        string strNewPath = string.Empty;

 

        if (FileUpload1.PostedFile != null)

        {

            strFilePath = FileUpload1.PostedFile.FileName;

            strFileType = FileUpload1.PostedFile.ContentType.ToString();

 

            System.IO.FileInfo fi = new System.IO.FileInfo(strFilePath);

            strFileName = fi.Name;

            strNewPath = @"D:\TempUploadFolder\" + strFileName;

 

            FileUpload1.SaveAs(strNewPath);

            lblUploadText.Text = strFileName + " 파일이 업로드되었습니다.";

            ReadContentInExcelFile(strNewPath, false);

        }

    }

 

    protected void ButtonUpload2_Click(object sender, EventArgs e)

    {

        string strFilePath = string.Empty;

        string strFileType = string.Empty;

        string strFileName = string.Empty;

        string strNewPath = string.Empty;

 

        if (FileUpload2.PostedFile != null)

        {

            strFilePath = FileUpload2.PostedFile.FileName;

            strFileType = FileUpload2.PostedFile.ContentType.ToString();

 

            System.IO.FileInfo fi = new System.IO.FileInfo(strFilePath);

            strFileName = fi.Name;

            strNewPath = @"D:\TempUploadFolder\" + strFileName;

 

            FileUpload2.SaveAs(strNewPath);

            lblUploadText.Text = strFileName + " 파일이 업로드되었습니다.";

            ReadContentInExcelFile(strNewPath, true);

        }

    }

 

    private void ReadContentInExcelFile(string strFilePath, bool bExcelVersion2007)

    {

        string strProvider = string.Empty;

 

        if (bExcelVersion2007)

        {

            strProvider = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + strFilePath + "; Extended Properties=Excel 12.0";

        }

        else

        {

            strProvider = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + strFilePath + "; Extended Properties=Excel 8.0";

        }

 

        string strQuery = "SELECT * FROM [Sheet1$]";

 

        OleDbConnection oleDBCon = null;

        OleDbCommand oleDBCom = null;

        OleDbDataReader oleDBReader = null;

 

        try

        {

            oleDBCon = new OleDbConnection(strProvider);

            oleDBCom = new OleDbCommand(strQuery, oleDBCon);

 

            oleDBCon.Open();

            oleDBReader = oleDBCom.ExecuteReader(CommandBehavior.CloseConnection);

 

            DataTable dtData = new DataTable();

            dtData.Load(oleDBReader);

 

            GridView1.DataSource = dtData.DefaultView;

            GridView1.DataBind();

        }

        catch (Exception ex)

        {

            Response.Write(ex.Source + "::" + ex.InnerException + "::" + ex.StackTrace);

        }

        finally

        {

            oleDBReader.Close();

            oleDBReader.Dispose();

            oleDBCon.Close();

        }

    }

}


소스 코드에 대해 간단하게 설명을 드리면, 2개의 FileUpload 컨트롤이 위치하고 있습니다. 위쪽의 FileUpload 컨트롤은 확장자가 "xls"인 Excel 97 또는 Excel 2000, Excel 2003 버전의 엑셀 파일의 업로드를 담당하게 됩니다. 아래쪽의 FileUpload 컨트롤은 확장자가 "xlsx"인 Excel 2007 버전의 엑셀 파일의 업로드를 담당하게 됩니다. 업로드 버튼을 클릭하면, 특정 폴더로 엑셀 파일을 저장한 후에 OleDB 클래스를 이용해서 엑셀 파일에 연결하게 됩니다.
이때, 확장자 "xls" 버전의 경우의 연결 정보와 확장자 "xlsx" 버전의 경우의 연결 정보가 다른 것에 주의하시기 바랍니다. "xlsx" 버전의 경우에는 프로바이더로 "Microsoft.ACE.OLEDB.12.0"을 사용하고 있으며 이 프로바이더를 사용하기 위해서는 http://www.microsoft.com/downloads/details.aspx?familyid=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=ko 에서 "2007 Office system 드라이버: 데이터 연결 구성 요소"를 다운로드받아 설치하셔야 합니다.

확장자 "xls"와 확장자 "xlsx" 엑셀 파일을 업로드하여 GridView에 출력한 화면은 각각 <그림 2>와 <그림 3>과 같습니다.


<그림 2> 확장자 "xls" 파일의 업로드 후 화면


<그림 3> 확장자 "xlsx" 파일의 업로드 후 화면


Creative Commons License
저작물크리에이티브 커먼즈 코리아 저작자표시-비영리-동일조건변경허락 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
border border
border border
  이전 포스트 :: #74. [ASP.NET 3.5] ListView 컨트롤 Part1
  다음 포스트 :: #76. [ASP.NET 3.5] ListView 컨트롤 Part2
border border
border border
  
# Commented By :: 조재문 At 3/27/2008 3:37:17 PM [M] [D]
참 좋은 정보입니다.
잘 배웠습니다.
항상 도움을 주는 이곳이 있어 기분이 좋군요..
늘 건강하세요.

DB로 옮기는 작업은 혼자 해볼까 합니다. (Linq to sql 로)
안되면 도움을....
# Commented By :: 최지훈 At 3/31/2008 10:46:54 AM [M] [D]
네, 좋은 정보였다니 다행입니다. ^^;;
재문님도 언제나 건강하세요~ ^^;;
# Commented By :: 이석 At 4/17/2008 6:55:19 PM [D]
'2007 Office system 드라이버: 데이터 연결 구성 요소'가 서버에만 깔려있으면 되는건가요?
시트 이름 'Sheet1'이 아니면 에러가 나는데
시트 이름을 동적으로 주려면 어떻게 해야 할나요??
# Commented By :: 최지훈 At 4/19/2008 3:52:14 PM [M] [D]
네. 업로드가 되는 서버에만 설치되어 있으면 됩니다.
시트 이름을 동적으로 주려면...
string strQuery = "SELECT * FROM [Sheet1$]";
라는 구문의 Sheet1을 조회할 시트명으로 대치해야겠네요...
만약 무조건 첫번째 시트를 조회하겠다... 하면... 방법은 찾아봐야겠죠. ^^;;
# Commented By :: 이석 At 4/21/2008 10:28:51 AM [D]
답변 감사합니다~
좋은 하루 되세요~
# Commented By :: ㅇㄷㅇ At 5/1/2008 10:38:21 AM [D]
데이터그리드가 아닌 Read() 로 읽어올시 첫행을 읽어오질 못합니다.
무슨방법이없나요?
# Commented By :: 최지훈 At 5/1/2008 1:42:22 PM [M] [D]
OleDbDataReader 클래스를 이용하여 엑셀 파일 정보를 불러올 때 그러한 경우가 종종 있습니다. 엑셀 파일 관련해서는 이방은님이 작성하신 엑셀 파일 정복하기(?)를 참고하시는게 좋습니다.

http://www.bangsil.pe.kr/Board/Read.aspx?BoardId=da05ba1b-3e9b-4d16-b8f8-ff2e4f7514c5&PostId=3e0e62d8-a02e-4e3e-bbc0-6c3dc6ba92d4
# Commented By :: 정진환 At 5/21/2008 4:24:08 PM [D]
///
/// a method that retrieves the worksheet names from the specified excel worksheet
///

/// excel document path
/// an array of worksheet names
public static string[] WorkSheetNames(string excelFilePath, string oledbProviderString)
{
//an array that would hold the extracted worksheet names
string[] workSheetNames;
//create a connection to the excel worksheet
using (OleDbConnection oledbConnection = new OleDbConnection(string.Format(oledbProviderString, excelFilePath)))
{
//open the connection
oledbConnection.Open();
// Get all of the Table names from the Excel workbook
DataTable dataTable = oledbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
//specify the dimension of the array
workSheetNames = new string[dataTable.Rows.Count];
//Add the Table name to the string array.
for (int i = 0; i < dataTable.Rows.Count; i++)
{
//append to the array the worksheet names
workSheetNames[i] = (string)dataTable.Rows[i]["TABLE_NAME"];
}
//close the connection
oledbConnection.Close();
}
//return the array
return workSheetNames;
}
---------------------------------------------------------------------------------------
위함수 추가 하시고

string[] WorkSheet = WorkSheetNames(strFilePath, strProvider);
string strQuery = "SELECT * FROM [" + WorkSheet[0] + "]";

가져온 워크시트 배열을 테이블 이름으로 사용하시면 됩니다.
# Commented By :: 김상욱 At 5/26/2008 3:55:47 PM [D]
감사합니다. 많은 도움 되었어요^^
# Commented By :: 최지훈 At 6/4/2008 4:14:22 PM [M] [D]
넵.... 도움이 되었다니 다행입니다. ^^;;
# Commented By :: jason At 11/5/2008 4:18:02 PM [D]
좋은정보 많은 도움이 되었습니다.
# Commented By :: 최지훈 At 11/11/2008 9:10:23 AM [M] [D]
도움이 되었다니 다행입니다. ^^;;
건승하세엽~!!!
# Commented By :: 나그네 At 12/10/2008 10:34:27 AM [D]
와우 감사합니다.
많은 도움 되었습니다.
# Commented By :: 박세준 At 5/18/2009 4:58:51 PM [D]
감사합니다.
덕분에 어려운 숙제의 실마리가 보이기 시작하네요^^
# Commented By :: 최지훈 At 5/25/2009 12:59:17 PM [M] [D]
음 다행이네요..
지금쯤이면 숙제는 Complete가 되었겠네요. ^^;;
# Commented By :: sung At 3/17/2010 7:27:43 PM [D]
안녕하세요...
좋은 정보 감사드립니다. 저 또한 엑셀 파일을 읽으면서 xls , xlsx 확장자땜에 좀 헤맸습니다..
그런데 엑셀파일은 읽을 수가 있는데 파워포인트 파일은 읽지를 못하네요...
ppt 파일을 읽을 수 있는 방법 혹시 알고 계시면 부탁드립니다.
# Commented By :: 최지훈 At 3/23/2010 6:15:46 PM [M] [D]
파워포인트 관련해서는 저도 잘 모르겠네요 ^^;;
도움을 못드려서 죄송합니다~
# Commented By :: @.@ At 3/29/2010 10:15:56 AM [D]
안녕하세요.. 정말 많은 도움 받았습니다. 제가 아직 초보라 access DB 연결은 했었는데..
Excel 은 잘 안되서요.. 일단 설명해주신대로 드라이버 다운을 받고 설치도 하였습니다.
그런데 참조추가에서 Excel12.0 이란 항목이 보이질 않아서요..
데이터베이스에 연결하기 보면 access 만 보이고 excel은 보이지 않습니다.
그럼.. 답변 기다리겠습니다.
# Commented By :: @.@ At 3/29/2010 11:00:42 AM [D]
위에 참조추가는 해결하였습니다. 그런데 GridView가 나타나지 않습니다.
업로드는 됐다고 나오는데.. ㅜㅠ
# Commented By :: 최지훈 At 3/29/2010 1:42:19 PM [M] [D]
엑셀 파일 업로드 경로가 맞는지 확인하시고요...
GridView와 연결하는 시트명이 Sheet1인지 확인하시기 바랍니다.
다른 경우라면 쿼리문을 바꾸어줘야햐겠죠..

또한, dtData.Load(oleDBReader); 후에
Row.Count를 이용하여 행의 개수를 확인해보시기 바랍니다.
Count가 0이면 나타나지 않을 수 있으니깐요...
# Commented By :: @.@ At 3/29/2010 2:24:43 PM [D]
답변 감사합니다. 그런데.. 시트명도 맞고.. 다 맞는데.. 아무것도 나오지 않네요.. ㅜㅠ
# Commented By :: 최지훈 At 3/31/2010 2:24:42 PM [M] [D]
흠... 왜 그런건지 잘 모르겠네요...
해결되면 좋겠네요. 화이팅~!!!
# Commented By :: 지노 At 6/7/2010 4:58:03 PM [D]
좋은정보 알아갑니다 ^^
멋져요~
# Commented By :: 최지훈 At 6/15/2010 8:23:45 AM [M] [D]
좋은 정보라 하니... 감사할 따름입니다. ^^;;
# Commented By :: 배성철 At 6/29/2010 4:25:53 PM [M] [D]
예제의 경우는 파일을 업로드하는게 로컬이자나요. 로컬이 아니고 서버로 올리고 그 파일을 읽어드리는 방법은 없나요?
  NAME ::   PASSWORD ::
  MAIL ::   HOMEPAGE ::
  COMMENT ::
border border
border border
COPYLEFT NX Blogs.   opml

LogIn ]  [ Join NX Blog's ]
border border
border border
mvp
border border
border border
  border
   Personal Thought
   ASP.NET
   ASP.NET AJAX
   ASP.NET MVC Framework
   Dev Story(Etc.)
   Reading the Articles
   About Microsoft / MSDN
   Certification Talk
   Useful Dev Tools
border border
border border
  border
   2010 년 09 월 (1)
   2010 년 06 월 (1)
   2010 년 05 월 (1)
   2010 년 04 월 (1)
   2010 년 03 월 (1)
   2010 년 02 월 (5)
   2010 년 01 월 (1)
   2009 년 04 월 (2)
   2009 년 03 월 (3)
   2009 년 02 월 (6)
   2009 년 01 월 (1)
   2008 년 10 월 (1)
   2008 년 06 월 (8)
   2008 년 05 월 (10)
   2008 년 04 월 (13)
   2008 년 03 월 (9)
   2008 년 02 월 (17)
   2008 년 01 월 (5)
   2007 년 12 월 (8)
   2007 년 11 월 (15)
   2007 년 10 월 (36)
   2007 년 09 월 (33)
   2007 년 08 월 (17)
   2007 년 07 월 (23)
   2007 년 06 월 (4)
   2007 년 05 월 (16)
   2007 년 04 월 (26)
   2007 년 03 월 (14)
   2007 년 02 월 (25)
   2007 년 01 월 (41)
   2006 년 12 월 (38)
   2006 년 11 월 (0)
   2006 년 10 월 (0)
   2006 년 09 월 (1)
   2006 년 08 월 (9)
   2006 년 07 월 (1)
border border
border border
  border
   #128. 無題
    By 최지훈 At 9/3/2010
   127. [예약구매] 실전. jQ...
    By 최지훈 At 6/13/2010
   #126. 무제
    By 최지훈 At 5/23/2010
   #125. 요즘 근황?
    By 최지훈 At 4/15/2010
   #124. ASP.NET 4 책을...
    By 최지훈 At 3/12/2010
   #97. ASP.NET 4 New...
    By 최지훈 At 2/12/2010
   #96. ASP.NET 4 New...
    By 최지훈 At 2/10/2010
   #95. ASP.NET 4 New...
    By 최지훈 At 2/9/2010
   #94. ASP.NET 4 New...
    By 최지훈 At 2/2/2010
   #93. ASP.NET 4 New...
    By 최지훈 At 2/1/2010
border border
border border
  border
   배는숨겨야지 에서 나도 모르게 빵...
    By ㅋㅋ At 8/17/2010
   Sorry. I don't hav...
    By 최지훈 At 8/16/2010
   내 생애 번역서는 이걸루 끝이다....
    By 최지훈 At 8/16/2010
   네..^^;; 저도 감사합니다.
    By 최지훈 At 8/16/2010
   IIS 버전이 업그레이드되면서 해...
    By 최지훈 At 8/16/2010
   나중에 비슷한 차로 태워는 줄께~...
    By 최지훈 At 8/16/2010
   나도 사주세요 저 차
    By ㅋㅋ At 8/12/2010
   저도 URL Rewriting 이...
    By 초보 At 8/7/2010
   감사드립니다^^
    By 이한철 At 7/28/2010
   오우~ 형 ㅊㅋㅊㅋ해~ 결국 했구...
    By 산티아고 At 7/26/2010
border border