【发布时间】:2018-11-28 18:18:46
【问题描述】:
我正在尝试通过 c# asp.net 网页将 excel 电子表格上传到 sql 数据库。 我不断收到错误消息:“Microsoft Office Access 数据库引擎找不到对象‘PPR_Status_Detailed’,请确保该对象存在并且您正确拼写了它的名称和路径名。”我不明白为什么,我已将连接字符串和工作表名称更改为,但仍然出现此错误。当我打开 excel 文件然后尝试上传它时,它显示“外部表不是预期格式”。我正在使用 .xls 和 .xlxs 文件
在 OleDbDataReader dr = oledbcmd.ExecuteReader(); 处失败
代码:
> public partial class Upload : System.Web.UI.Page {
> string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["PostbankConnectionString"].ConnectionString;
> protected void Page_Load(object sender, EventArgs e)
> {
>
> }
>
> public void importdatafromexcel(string excelfilepath)
> {
> //declare variables - edit these based on your particular situation
> string ssqltable = "PPRS";
> // make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have different
> string myexceldataquery = "Select * FROM [PPR_Status_Detailed]";
> try
> {
> //create our connection strings
> string sexcelconnectionstring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelfilepath +
> ";Extended Properties=" + "\"excel 12.0;hdr=yes;\"";
>
> string sclearsql = "TRUNCATE TABLE " + ssqltable;
> SqlConnection sqlconn = new SqlConnection(strConnString);
> SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
> sqlconn.Open();
> sqlcmd.ExecuteNonQuery();
>
> //series of commands to bulk copy data from the excel file into our sql table
> OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
> OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
> oledbconn.Open();
> OleDbDataReader dr = oledbcmd.ExecuteReader();
>
> SqlBulkCopy bulkcopy = new SqlBulkCopy(strConnString);
> bulkcopy.DestinationTableName = ssqltable;
> //Mapping Table column
>
> bulkcopy.ColumnMappings.Add("Task ID","[Task_ID]");
> bulkcopy.ColumnMappings.Add("PPR Caption", "[PPR_Caption]");
> bulkcopy.ColumnMappings.Add("Project Start Date", "[Project_StartDate]");
> bulkcopy.ColumnMappings.Add("Project End Date", "[Project_EndDate]");
> bulkcopy.ColumnMappings.Add("Current Task", "[Current_Task]");
> bulkcopy.ColumnMappings.Add("User", "[User]");
>
>
>
> sqlcmd.ExecuteNonQuery();
> while (dr.Read())
> {
> bulkcopy.WriteToServer(dr);
> }
>
> oledbconn.Close();
> sqlconn.Close();
>
> }
>
> catch (Exception)
> {
> //handle exception
> }
> }
>
>
> }
>
> protected void Button1_Click(object sender, EventArgs e) {
> string CurrentFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);
> importdatafromexcel(CurrentFilePath); } }
【问题讨论】:
-
你知道它在哪一行失败了吗? Excel 工作表总是以 $ 结尾,因此您的 SQL 应该是 Select * From [PPR_Status_Detailed$]
-
我添加了 $ 符号,现在我的错误显示 The given ColumnName 'Task ID' does not match up with any column in data source." 我的所有列都匹配并且数据库中列的数据类型是 nvarchar(max) –
标签: c# asp.net sql-server oledb