ssouf
ASP.NET을 이용한 Excel 파일 읽어오기 본문
프로젝트를 수행하면서, 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" />
<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" />
<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();
}
}
}
'Web DEV > ASP..NET' 카테고리의 다른 글
이클립스 에서 tfspreview.com 사용하기! (0) | 2012.07.14 |
---|---|
TFS 서버 없이 소스제어 !! tfspreview.com (0) | 2012.07.13 |
pageUrl에 해당하는 페이지 요청을 생성해 응답으로 넘어오는 스트림을 문자열에 담아 결과 값을 문자열로 반환 (0) | 2009.12.10 |
대용량 데이터 다운로드 (0) | 2009.12.10 |
Byte[] 를 File로 만드는 방법 (0) | 2009.12.10 |