使用asp.net读取并显示excel数据


Microsoft Office Excel是一个很好的电子表格应用程序,在本文中,it同学会将教给你看到如何使用ASP.NET从Excel电子表格读取并显示显示数据。

我们的ASP页面将在远程服务器上,来读取我们的桌面Excel文件。首先,我们必须把它上传到远程服务器,然后retrive数据。因此,我们首先设计一个表格,上传到服务器。我们必须从文件retrive数据,再一次,所以我们将重新命名Excel,然后上传。

  1. <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> 
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
  3. <html xmlns="http://www.w3.org/1999/xhtml"> 
  4. <head runat="server"> 
  5. <title>Read and Display Data From an Excel File (.xsl or .xlsx) in ASP.NET</title> 
  6. <style type="text/css">   
  7. tr.sectiontableentry1 td,  
  8. tr.sectiontableentry2 td {  
  9. padding: 4px;  
  10. }  
  11. tr.sectiontableentry1 td {  
  12. padding: 8px 5px;  
  13. background: url(hline.gif) repeat-x bottom;  
  14. }  
  15. tr.sectiontableentry2 td {  
  16. padding: 8px 5px;  
  17. background: url(hline.gif) repeat-x bottom #F2F2F2;  
  18. }  
  19. </style> 
  20. </head> 
  21. <body> 
  22. <form id="form1" runat="server"> 
  23. <div> 
  24. <table style="padding: 5px; font-size: 11px;" align="center" border="0"> 
  25. <tbody> 
  26. <tr> 
  27. <td> 
  28. <strong>Please Select Excel file containing job details…</strong> 
  29. </td> 
  30. </tr> 
  31. <tr> 
  32. <td> 
  33. <div style="background: url(hline.gif) repeat-x bottom #F2F2F2;padding: 8px 5px;border-bottom: 1px solid #ccc;"> 
  34. <asp:FileUpload ID="txtFilePath" runat="server"></asp:FileUpload>&nbsp;&nbsp;  
  35. <asp:Button ID="btnUpload" runat="server" Text="Upload" /><br />   
  36. <asp:Label ID="lblMessage" runat="server" Visible="False" Font-Bold="True"   
  37. ForeColor="#009933"></asp:Label> 
  38. </div> 
  39. </td> 
  40. </tr> 
  41. <tr> 
  42. <td> 
  43. <asp:GridView ID="dtgJobs" runat="server"> 
  44. <RowStyle CssClass="sectiontableentry2" /> 
  45. <AlternatingRowStyle CssClass="sectiontableentry1" /> 
  46. </asp:GridView>   
  47. </td> 
  48. </tr> 
  49. </tbody> 
  50. </table> 
  51. </div> 
  52. </form> 
  53. </body> 
  54. </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的$]是两个不同的查询。

VB.NET CODE:

  1. Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click  
  2. If (txtFilePath.HasFile) Then 
  3. Dim conn As OleDbConnection  
  4. Dim cmd As OleDbCommand  
  5. Dim da As OleDbDataAdapter  
  6. Dim ds As DataSet  
  7. Dim query As String 
  8. Dim connString As String = "" 
  9. Dim strFileName As String = DateTime.Now.ToString("ddMMyyyy_HHmmss")  
  10. Dim strFileType As String = System.IO.Path.GetExtension(txtFilePath.FileName).ToString().ToLower()  
  11.    
  12. ‘Check file type  
  13. If strFileType.Trim = ".xls" Or strFileType.Trim = ".xlsx" Then 
  14. txtFilePath.SaveAs(Server.MapPath("~/UploadedExcel/" & strFileName & strFileType))  
  15. Else 
  16. lblMessage.Text = "Only excel files allowed" 
  17. lblMessage.ForeColor = Drawing.Color.Red  
  18. lblMessage.Visible = True 
  19. Exit Sub 
  20. End If 
  21.    
  22. Dim strNewPath As String = Server.MapPath("~/UploadedExcel/" & strFileName & strFileType)  
  23.    
  24. ‘Connection String to Excel Workbook  
  25. If strFileType.Trim = ".xls" Then 
  26. connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strNewPath & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2""" 
  27. ElseIf strFileType.Trim = ".xlsx" Then 
  28. connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strNewPath & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2""" 
  29. End If 
  30.    
  31. query = "SELECT * FROM [Sheet1$]" 
  32.    
  33. ‘Create the connection object   
  34. conn = New OleDbConnection(connString)  
  35. ‘Open connection  
  36. If conn.State = ConnectionState.Closed Then conn.Open()  
  37. ‘Create the command object  
  38. cmd = New OleDbCommand(query, conn)  
  39. da = New OleDbDataAdapter(cmd)  
  40. ds = New DataSet()  
  41. da.Fill(ds)  
  42.    
  43. grvExcelData.DataSource = ds.Tables(0)  
  44. grvExcelData.DataBind()  
  45.    
  46. da.Dispose()  
  47. conn.Close()  
  48. conn.Dispose()  
  49. Else 
  50. lblMessage.Text = "Please select an excel file first" 
  51. lblMessage.ForeColor = Drawing.Color.Red  
  52. lblMessage.Visible = True 
  53. End If 
  54. End Sub   

C#.NET Code

  1. protected void btnUpload_Click(object sender, EventArgs e)  
  2. {  
  3. if ((txtFilePath.HasFile))  
  4. {  
  5.    
  6. OleDbConnection conn = new OleDbConnection();  
  7. OleDbCommand cmd = new OleDbCommand();  
  8. OleDbDataAdapter da = new OleDbDataAdapter();  
  9. DataSet ds = new DataSet();  
  10. string query = null;  
  11. string connString = "";  
  12. string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");  
  13. string strFileType = System.IO.Path.GetExtension(txtFilePath.FileName).ToString().ToLower();  
  14.    
  15. //Check file type  
  16. if (strFileType == ".xls" || strFileType == ".xlsx")  
  17. {  
  18. txtFilePath.SaveAs(Server.MapPath("~/UploadedExcel/" + strFileName + strFileType));  
  19. }  
  20. else 
  21. {  
  22. lblMessage.Text = "Only excel files allowed";  
  23. lblMessage.ForeColor = System.Drawing.Color.Red;  
  24. lblMessage.Visible = true;  
  25. return;  
  26. }  
  27.    
  28. string strNewPath = Server.MapPath("~/UploadedExcel/" + strFileName + strFileType);  
  29.    
  30. //Connection String to Excel Workbook  
  31. if (strFileType.Trim() == ".xls")  
  32. {  
  33. connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";  
  34. }  
  35. else if (strFileType.Trim() == ".xlsx")  
  36. {  
  37. connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";  
  38. }  
  39.    
  40. query = "SELECT * FROM [Sheet1$]";  
  41. //query = "SELECT [Country],[Capital] FROM [Sheet1$] WHERE [Currency]=’Rupee’"  
  42. //query = "SELECT [Country],[Capital] FROM [Sheet1$]"  
  43.    
  44. //Create the connection object  
  45. conn = new OleDbConnection(connString);  
  46. //Open connection  
  47. if (conn.State == ConnectionState.Closed) conn.Open();  
  48. //Create the command object  
  49. cmd = new OleDbCommand(query, conn);  
  50. da = new OleDbDataAdapter(cmd);  
  51. ds = new DataSet();  
  52. da.Fill(ds);  
  53.    
  54. grvExcelData.DataSource = ds.Tables[0];  
  55. grvExcelData.DataBind();  
  56.    
  57. lblMessage.Text = "Data retrieved successfully! Total Records:" + ds.Tables[0].Rows.Count;  
  58. lblMessage.ForeColor = System.Drawing.Color.Green;  
  59. lblMessage.Visible = true;  
  60.    
  61. da.Dispose();  
  62. conn.Close();  
  63. conn.Dispose();  
  64. }  
  65. else 
  66. {  
  67. lblMessage.Text = "Please select an excel file first";  
  68. lblMessage.ForeColor = System.Drawing.Color.Red;  
  69. lblMessage.Visible = true;  
  70. }  
  71. }   

ittxh.cn使用上面的代码进行测试,得到的结果如下所示:

以上就是使用asp.net读取并显示excel数据


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3