我尝试从Excel文件中加载一个GridView,但是我得到了以下错误:
Microsoft Jet数据库引擎“Sheet1 $”无法找到对象。请确保该对象存在且名称拼写正确以及路径正确。
并且在这一行中出现错误:excelDataAdapter.Fill(dt);
我在App_Data文件夹中有一个.xls文件。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Data;
using System.Data.OleDb;
namespace Excell
{
public partial class LoadExcelToGrid: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
gv.DataSource = exceldata(Server.MapPath("~/data.xls"));
gv.DataBind();
}
public static DataSet exceldata(string filelocation)
{
DataSet ds = new DataSet();
OleDbCommand excelCommand = new OleDbCommand(); OleDbDataAdapter excelDataAdapter = new
OleDbDataAdapter();
string excelConnStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + filelocation +
"; Extended Properties=Excel 8.0;";
OleDbConnection excelConn = new OleDbConnection(excelConnStr);
excelConn.Open();
DataTable dt = new DataTable();
excelCommand = new OleDbCommand("Select * from [Sheet1$]", excelConn);
excelDataAdapter.SelectCommand = excelCommand;
excelDataAdapter.Fill(dt);
ds.Tables.Add(dt);
return ds;
}
}
}