gpt4 book ai didi

c# - 如何通过 c# 从 asp.net 中的 excel 文件加载 gridview?

转载 作者:行者123 更新时间:2023-11-30 14:12:23 26 4
gpt4 key购买 nike

我尝试从 excel 文件加载一个 gridview。但是我得到了这个错误

Microsoft Jet 数据库引擎“Sheet1 $”找不到对象。确保该对象存在并且其名称和路径拼写正确。

这一行有一个错误:excelDataAdapter.Fill(dt);

我在 App_Data 文件夹中有一个 .xls 文件。Wh

 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;
}


}
}

最佳答案

此代码适用于我。

protected void btnUpload_Click(object sender, EventArgs e)
{
String strConnection = "ConnectionString";
string connectionString ="";
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
FileUpload1.SaveAs(fileLocation);
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName +"]";
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dtExcelRecords);
GridView1.DataSource = dtExcelRecords;
GridView1.DataBind();
}

关于c# - 如何通过 c# 从 asp.net 中的 excel 文件加载 gridview?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17808141/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com