程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> asp.net 讀取並顯示excel數據的實現代碼

asp.net 讀取並顯示excel數據的實現代碼

編輯:ASP.NET基礎
我們的ASP頁面將在遠程服務器上,來讀取我們的桌面Excel文件。首先,我們必須把它上傳到遠程服務器,然後retrive數據。因此,我們首先設計一個表格,上傳到服務器。我們必須從文件retrive數據,再一次,所以我們將重新命名Excel,然後上傳。
復制代碼 代碼如下:
<%@ 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>  
<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驅動程序,也是閱讀Excel 2003的能力。我們將用它來閱讀xlsx(Excel 2007年)的數據。
我們有一個Excel文件,其內容如下所示。注意:此表名稱必須相同,意味著,如果想讀的Sheet1的數據。你必須小心,同時書面方式的SQL查詢,因為選擇*從[Sheet1的$]和SELECT *從[Sheet1的$]是兩個不同的查詢。
使用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讀取並顯示excel數據
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved