gpt4 book ai didi

c# - Microsoft Office Access 数据库引擎找不到对象

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

我正在尝试将数据从 excel 复制到 sql server 但遇到以下错误。

The Microsoft Office Access database engine could not find the object 'sheet1$'. Make sure the object exists and that you spell its name and the path name correctly.

我的代码是:

 protected void importdatafromexcel(string filepath)
{
string sqltable = "PFDummyExcel";
string exceldataquery = "select EmployeeId,EmployeeName,Amount from [Sheet1$]";
string excelconnectionstring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=Excel 12.0;Persist Security Info=False";
string sqlconnectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["HRGold"].ConnectionString;
SqlConnection con = new SqlConnection(sqlconnectionstring);
OleDbConnection oledb = new OleDbConnection(excelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(exceldataquery, oledb);
oledb.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(sqlconnectionstring);
bulkcopy.DestinationTableName = sqltable;
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
oledb.Close();
}

请告诉我如何解决这个问题..

最佳答案

出现此错误是因为您正在尝试访问 excel 文件中的工作表(名称为 sheet1)。默认情况下,第一个工作表名称为“sheet1”,但用户可以重命名此名称或删除此工作表。

要解决此问题,首先您必须从 excel 文件中获取所有工作表名称,然后您必须在上述代码中传递此工作表名称以导入数据。

string  filePath = "your file path";

string excelconnectionstring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=Excel 12.0;Persist Security Info=False";

OleDbConnection Connection = new OleDbConnection(excelconnectionstring);


DataTable activityDataTable = Connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

if(activityDataTable != null)
{
//validate worksheet name.
var itemsOfWorksheet = new List<SelectListItem>();
string worksheetName;
for (int cnt = 0; cnt < activityDataTable.Rows.Count; cnt++)
{
worksheetName = activityDataTable.Rows[cnt]["TABLE_NAME"].ToString();

if (worksheetName.Contains('\''))
{
worksheetName = worksheetName.Replace('\'', ' ').Trim();
}
if (worksheetName.Trim().EndsWith("$"))
itemsOfWorksheet.Add(new SelectListItem { Text = worksheetName.TrimEnd('$'), Value = worksheetName });
}
}

// itemsOfWorksheet : all worksheet name is added in this

因此您可以使用 itemsOfWorksheet[0] 作为工作表名称来代替“sheet1”

关于c# - Microsoft Office Access 数据库引擎找不到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20417626/

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