如何使用C#在ASP.NET中打开Excel文件

时间:2011-10-31 18:45:31

标签: c# excel

我有一个excel文件,我需要打开并搜索它。这是我使用的代码:

public partial class _Default : System.Web.UI.Page 
{
string connStr;
string absoluteDir;
string relativeDir;

protected void Page_Load(object sender, EventArgs e)
{
    relativeDir = "~/data" + System.IO.Path.DirectorySeparatorChar + "zadacaEXCEL.xlsx";
    absoluteDir = Server.MapPath( relativeDir );
    Label1.Text = absoluteDir + "      ";
    connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + absoluteDir + ";Extended Properties=\"Excel 8.0;HDR=Yes\"";
    //string connString = ConfigurationManager.ConnectionStrings["xls"].ConnectionString;
    // Create the connection object

    OleDbConnection oledbConn = new OleDbConnection(connStr);
    try
    {
        // Open connection
        oledbConn.Open();

        // Create OleDbCommand object and select data from worksheet Sheet1
        OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);

        // Create new OleDbDataAdapter
        OleDbDataAdapter oleda = new OleDbDataAdapter();

        oleda.SelectCommand = cmd;

        // Create a DataSet which will hold the data extracted from the worksheet.
        DataSet ds = new DataSet();

        // Fill the DataSet from the data extracted from the worksheet.
        oleda.Fill(ds);

        // Bind the data to the GridView
        GridView1.DataSource = ds.Tables[0].DefaultView;
        GridView1.DataBind();
    }
    catch(Exception err)
    {
        Label1.Text += err.ToString();
    }
    finally
    {
        // Close connection
        oledbConn.Close();
    } 
}

这是我得到的错误:

System.Data.OleDb.OleDbException: External table is not in the expected format. at 
System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection) at 
System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) at
System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) at 
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at 
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at 
System.Data.OleDb.OleDbConnection.Open() at 
_Default.Page_Load(Object sender, EventArgs e) in c:\Users\ACO\Documents\Visual Studio 2008\WebSites\za_rabota\Default.aspx.cs:line 33

错误发生在oledbConn.Open();

有人可以告诉我这里我做错了什么。 excel文件位于解决方案中名为data的文件夹中

1 个答案:

答案 0 :(得分:2)

Excel 2007及更高版本的文件(以.xslx结尾)的提供程序类型和字符串不正确。您需要使用OLEDB 12.0 connection string

类似的东西:

connStr  = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + absoluteDir + ";Extended Properties="Excel 12.0 Xml;HDR=YES";