0

在这里,用户从那里系统浏览到 Excel 文件,然后将数据上传到 sql 数据库表。

我在以下代码中收到此错误:Microsoft Jet 数据库引擎找不到对象“C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\Student Registration1.xls”。确保对象存在并且正确拼写其名称和路径名。

我不知道为什么它要求这条 Path ?C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\

protected void import_xls_Click(object sender, EventArgs e)
    {
        try
        {
            if (xmlupload.HasFile)
            {
                string path = xmlupload.PostedFile.FileName;


                string excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";

                OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
                excelConnection.Open();

                OleDbCommand cmd = new OleDbCommand("select * from [Sheet2$]", excelConnection);                    
                OleDbDataReader dReader = cmd.ExecuteReader();

                SqlBulkCopy sqlBulk = new SqlBulkCopy(SqlConnectionstring.mainConnectionString, SqlBulkCopyOptions.KeepIdentity);

                sqlBulk.DestinationTableName = "dbo.studentA";                    
                sqlBulk.ColumnMappings.Add("UserName", "UserName");
                sqlBulk.ColumnMappings.Add("Password", "Password");
                sqlBulk.ColumnMappings.Add("Name", "Name");
                sqlBulk.ColumnMappings.Add("Standard", "Standard");
                sqlBulk.ColumnMappings.Add("Division", "Division");
                sqlBulk.ColumnMappings.Add("SchoolName", "SchoolName");
                sqlBulk.ColumnMappings.Add("Language", "Language");
                sqlBulk.ColumnMappings.Add("ExamStatus", "ExamStatus");
                sqlBulk.ColumnMappings.Add("Result", "Result");                   

                sqlBulk.WriteToServer(dReader);

                lblmsg.Visible = true;
                lblmsg.Text = "Your data uploaded successfully";
                excelConnection.Close();
            }
        }
        catch (Exception ex)
        {
            lblmsg.Visible = true;
            lblmsg.Text = ex.Message.ToString();

        }

SqlConnectionstring.cs:

public class SqlConnectionstring
{
public SqlConnectionstring()
{
    //
    // TODO: Add constructor logic here
    //
}


public static readonly string mainConnectionString = ConfigurationManager.ConnectionStrings["constring"].ToString();
}
4

1 回答 1

3

我将尝试将文件保存在工作目录中,然后尝试从那里打开。
如果文件名没有路径,则连接只有在
当前目录中才能找到该文件(通常是您的程序开始的位置)

string savePath = @"c:\temp\uploads";

if (xmlupload.HasFile)
{
  string fileName = xmlupload.FileName;
  savePath = Path.Combine(savePath, fileName);
  xmlupload.SaveAs(savePath);
  string excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + 
                      savePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";   

  ....

在 Web 服务器上,为避免权限问题,最好将文件保存在站点根文件夹的子文件夹中。

在这种情况下,可以使用HttpServerUtility.MapMath方法完全限定文件夹。

于 2012-08-11T21:07:05.007 回答