ASP.net读取Excel

web.config中的配置字符串:
<appSettings>
   <add key="DataPath1" value="db/Data.xls" />
</appSettings>

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Text;
using System.Configuration;

namespace my
{
    
/// <summary>
    
/// excel 的摘要说明。
    
/// </summary>

    public class excel : System.Web.UI.Page
    
{
        
public static string strConn
        
{
            
get
            
{
                StringBuilder builder1 
= new StringBuilder();
                builder1.Append(
"Provider = Microsoft.Jet.OLEDB.4.0");
                builder1.Append(
"");
                builder1.Append(
"Extended Properties=Excel 8.0");
                builder1.Append(
"");
                builder1.Append(
"Data Source = ");
                builder1.Append(HttpContext.Current.Server.MapPath(
"."));
                builder1.Append(
@"\");
                builder1.Append(ConfigurationSettings.AppSettings[
"DataPath1"]);
                
return builder1.ToString();
            }

        }

        
protected System.Web.UI.WebControls.DataGrid DataGrid1;
    
        
private void Page_Load(object sender, System.EventArgs e)
        
{
            OleDbConnection conn 
= new OleDbConnection(strConn);
            OleDbCommand com 
=new OleDbCommand("SELECT * FROM [Sheet1$]",conn);
            OleDbDataAdapter da
=new OleDbDataAdapter(com);
            DataSet ds
=new DataSet();
            da.Fill(ds);
            DataGrid1.DataSource
=ds.Tables[0].DefaultView;
            DataGrid1.DataBind();
        }


        
Web 窗体设计器生成的代码
    }

}

其中的[Sheet1$]为Excel中的表,如出现 Microsoft Jet 数据库引擎找不到对象'Sheet1$'
则是数据库的路径的问题,而不是Excel中表的问题
posted @ 2005-11-02 16:37  therockthe  阅读(1898)  评论(1)    收藏  举报