1

我确实将数据从 Excel 表导入到 Sql 数据库..一切都很好,当我运行此代码时,我的访问引擎找不到 mt 表,它会抛出这个错误..我的错误是

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

但我已经检查了我的指定文件夹,它是正确的..然后我不知道为什么它会重复

我的 C# 代码如下..

public partial class _Default : System.Web.UI.Page 
{
    string constr = @"Data Source=VIS1-B12\SQLEXPRESS;Initial Catalog=Sql_Excel;Integrated Security=True providerName=System.Data.SqlClient" ;

    protected void btn_okClick(object sender, EventArgs e)
    {
        string path = Fup_Excel.PostedFile.FileName;
        string exconstr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+path+";Extended Properties=Excel 8.0";

        OleDbConnection excelcon = new OleDbConnection(exconstr);
        excelcon.Open();

        OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", excelcon);
        OleDbDataReader dbreader;
        OleDbDataAdapter dap = new OleDbDataAdapter(cmd);
        DataSet ds = new DataSet();
        //dap.Fill(ds,"sheet1");
        dbreader = cmd.ExecuteReader();

        SqlBulkCopy bcpy = new SqlBulkCopy(constr);
        bcpy.DestinationTableName = "Excel_Details";
        bcpy.WriteToServer(dbreader);
        //GridView1.DataSource = ds.Tables[0].DefaultView;
        //GridView1.DataBind();
        excelcon.Close();
    }
}
4

1 回答 1

0

最好使用代码检索 excel 工作表名称。
代码如下所示

OleDbConnection con = new OleDbConnection(ConnString);
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);
于 2012-10-15T11:53:51.787 回答