0

我正在尝试将 excel 工作表的数据导入 sql server 数据库中的表中,但出现错误:Microsoft Office Access 数据库引擎找不到对象“Sheet1$”。确保对象存在并且正确拼写其名称和路径名。

以下是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Data.OleDb;

public partial class abc2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void btnSend_Click(object sender, EventArgs e)
    {
         String strConnection = "Data Source=DITSEC3;Initial Catalog=test;Integrated Security=True";
         //file upload path
         string path = fileuploadExcel.PostedFile.FileName;
         //Create connection string to Excel work book
         string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;Persist Security Info=False";
         //Create Connection to Excel work book
         OleDbConnection excelConnection =new OleDbConnection(excelConnectionString);
         //Create OleDbCommand to fetch data from Excel
         OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from    [Sheet1$]",excelConnection);
         excelConnection.Open();
         OleDbDataReader dReader;
         dReader = cmd.ExecuteReader();
         SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
         //Give your Destination table name
         sqlBulk.DestinationTableName = "Excel_table";
         sqlBulk.WriteToServer(dReader);
         excelConnection.Close();
    }
}
4

2 回答 2

0

我认为您尝试导入的 excel 工作表的名称与 $sheet1 不同,因此,要获取工作表名称,请使用以下代码并将工作表的名称传递给 sql 查询以从工作表中获取数据。

http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/05c92891-b839-45c8-80df-eb35e2d68258

于 2012-10-23T09:22:24.360 回答
0

Excel.Application ExcelObj = new Excel.Application();

Excel.Workbook theWorkbook = null;

string strPath="在此处提及 EXCEL 文件的路径"; theWorkbook = ExcelObj.Workbooks.Open(strPath,失踪,失踪,失踪,失踪,失踪,失踪,失踪,失踪,失踪,失踪,失踪,失踪,失踪,失踪);

Excel.Sheets 工作表 = theWorkbook.Worksheets;

Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(0);//获取第二个工作表字符串的引用 strWorksheetName = worksheet.Name;//获取工作表的名称。

并在选择查询中使用 strWorksheetName 来获取列数据

于 2012-10-23T09:58:58.370 回答