我试图将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();
}
}
答案 0 :(得分:0)
我认为您尝试导入的Excel工作表的名称不同于$ sheet1,因此要获取工作表名称使用以下代码并将该工作表名称传递给sql查询以从工作表中获取数据。
http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/05c92891-b839-45c8-80df-eb35e2d68258
答案 1 :(得分:0)
Excel.Application ExcelObj = new Excel.Application();
Excel.Workbook theWorkbook = null;
string strPath =“EX EXEL FILE HERE的路径”; theWorkbook = ExcelObj.Workbooks.Open(strPath,缺失,丢失,丢失,丢失,丢失,丢失,丢失,丢失,丢失,丢失,丢失,丢失,丢失,丢失);
Excel.Sheets sheets = theWorkbook.Worksheets;
Excel.Worksheet worksheet =(Excel.Worksheet)sheets.get_Item(0); //获取引用 第二个工作表字符串strWorksheetName = worksheet.Name; //获取工作表的名称。
并在select query中使用strWorksheetName来获取列数据