asp.net 읽 기 및 엑셀 데이터 구현 코드 표시

우리 의 ASP 페이지 는 원 격 서버 에서 데스크 톱 Excel 파일 을 읽 을 것 입 니 다.우선,우 리 는 그것 을 원 격 서버 에 업로드 한 후에 retrive 데 이 터 를 해 야 한다.그래서 우 리 는 먼저 표를 만들어 서버 에 업로드 합 니 다.파일 retrive 데이터 에서 다시 한 번 해 야 하기 때문에 엑셀 이름 을 바 꾸 고 업로드 할 것 입 니 다.
 
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Read and Display Data From an Excel File (.xsl or .xlsx) in ASP.NET</title>
<style type="text/css">
tr.sectiontableentry1 td,
tr.sectiontableentry2 td {
padding: 4px;
}
tr.sectiontableentry1 td {
padding: 8px 5px;
background: url(hline.gif) repeat-x bottom;
}
tr.sectiontableentry2 td {
padding: 8px 5px;
background: url(hline.gif) repeat-x bottom #F2F2F2;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="padding: 5px; font-size: 11px;" align="center" border="0">
<tbody>
<tr>
<td>
<strong>Please Select Excel file containing job details…</strong>
</td>
</tr>
<tr>
<td>
<div style="background: url(hline.gif) repeat-x bottom #F2F2F2;padding: 8px 5px;border-bottom: 1px solid #ccc;">
<asp:FileUpload ID="txtFilePath" runat="server"></asp:FileUpload>&nbsp;&nbsp;
<asp:Button ID="btnUpload" runat="server" Text="Upload" /><br />
<asp:Label ID="lblMessage" runat="server" Visible="False" Font-Bold="True"
ForeColor="#009933"></asp:Label>
</div>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="dtgJobs" runat="server">
<RowStyle CssClass="sectiontableentry2" />
<AlternatingRowStyle CssClass="sectiontableentry1" />
</asp:GridView>
</td>
</tr>
</tbody>
</table>
</div>
</form>
</body>
</html>
연결 은 Microsoft OLE DB 가 제공 하 는 Excel jet 를 사용 하여 Microsoft OLE DB 에서 Jet(연합 엔진 기술 소 는 데이터베이스 엔진)이 제공 하 는 OLE DB 인터페이스,Microsoft Access 데이터 베 이 스 를 제공 하고 SQL Server 2005 와 더 높 은 분포 식 조 회 를 통 해 Access 데이터베이스 와 Excel 전자 표를 조회 할 수 있 도록 합 니 다.Microsoft Excel 워 크 북 에 연결 하여 Jet 4.0 의 Microsoft OLE DB 를 사용 하여 데 이 터 를 읽 고 GridView 에 표 시 된 데 이 터 를 제공 합 니 다.xlsx(Excel 2007 년)에는 공급 자 Microsoft.ACE.OLEDB.12.0 이 실 려 있 습 니 다.새로운 Access 데이터베이스 엔진 의 OLE DB 드라이버 이자 엑셀 2003 을 읽 는 능력 이다.우 리 는 그것 으로 xlsx(Excel 2007 년)의 데 이 터 를 읽 을 것 이다.우 리 는 엑셀 파일 을 하나 가지 고 있 는데,그 내용 은 아래 와 같다.메모:이 표 의 이름 은 같 아야 합 니 다.읽 고 싶 은 Sheet 1 의 데 이 터 를 의미 합 니 다.[Sheet 1 의$]와 SELECT*에서[Sheet 1 의$]를 선택 하 는 것 은 서로 다른 조회 이기 때문에 조심해 야 합 니 다.使用asp.net读取excel
 
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
If (txtFilePath.HasFile) Then
Dim conn As OleDbConnection
Dim cmd As OleDbCommand
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim query As String
Dim connString As String = ""
Dim strFileName As String = DateTime.Now.ToString("ddMMyyyy_HHmmss")
Dim strFileType As String = System.IO.Path.GetExtension(txtFilePath.FileName).ToString().ToLower()
‘Check file type
If strFileType.Trim = ".xls" Or strFileType.Trim = ".xlsx" Then
txtFilePath.SaveAs(Server.MapPath("~/UploadedExcel/" & strFileName & strFileType))
Else
lblMessage.Text = "Only excel files allowed"
lblMessage.ForeColor = Drawing.Color.Red
lblMessage.Visible = True
Exit Sub
End If
Dim strNewPath As String = Server.MapPath("~/UploadedExcel/" & strFileName & strFileType)
‘Connection String to Excel Workbook
If strFileType.Trim = ".xls" Then
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strNewPath & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2"""
ElseIf strFileType.Trim = ".xlsx" Then
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strNewPath & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
End If
query = "SELECT * FROM [Sheet1$]"
‘Create the connection object
conn = New OleDbConnection(connString)
‘Open connection
If conn.State = ConnectionState.Closed Then conn.Open()
‘Create the command object
cmd = New OleDbCommand(query, conn)
da = New OleDbDataAdapter(cmd)
ds = New DataSet()
da.Fill(ds)
grvExcelData.DataSource = ds.Tables(0)
grvExcelData.DataBind()
da.Dispose()
conn.Close()
conn.Dispose()
Else
lblMessage.Text = "Please select an excel file first"
lblMessage.ForeColor = Drawing.Color.Red
lblMessage.Visible = True
End If
End Sub
C\#.NET Code
 
protected void btnUpload_Click(object sender, EventArgs e)
{
if ((txtFilePath.HasFile))
{
OleDbConnection conn = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter da = new OleDbDataAdapter();
DataSet ds = new DataSet();
string query = null;
string connString = "";
string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");
string strFileType = System.IO.Path.GetExtension(txtFilePath.FileName).ToString().ToLower();
//Check file type
if (strFileType == ".xls" || strFileType == ".xlsx")
{
txtFilePath.SaveAs(Server.MapPath("~/UploadedExcel/" + strFileName + strFileType));
}
else
{
lblMessage.Text = "Only excel files allowed";
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Visible = true;
return;
}
string strNewPath = Server.MapPath("~/UploadedExcel/" + strFileName + strFileType);
//Connection String to Excel Workbook
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
query = "SELECT * FROM [Sheet1$]";
//query = "SELECT [Country],[Capital] FROM [Sheet1$] WHERE [Currency]='Rupee'"
//query = "SELECT [Country],[Capital] FROM [Sheet1$]"
//Create the connection object
conn = new OleDbConnection(connString);
//Open connection
if (conn.State == ConnectionState.Closed) conn.Open();
//Create the command object
cmd = new OleDbCommand(query, conn);
da = new OleDbDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
grvExcelData.DataSource = ds.Tables[0];
grvExcelData.DataBind();
lblMessage.Text = "Data retrieved successfully! Total Records:" + ds.Tables[0].Rows.Count;
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Visible = true;
da.Dispose();
conn.Close();
conn.Dispose();
}
else
{
lblMessage.Text = "Please select an excel file first";
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Visible = true;
}
}
은 위의 코드 를 사용 하여 테스트 한 결과 다음 과 같다.使用asp.net读取excel 이상 은 asp.net 을 사용 하여 엑셀 데 이 터 를 읽 고 표시 하 는 것 이다.

좋은 웹페이지 즐겨찾기