0

我正在开发一个具有文件上传、按钮和网格视图的网络表单。用户可以将 excel 文件上传到数据库,还可以在 gridview 中查看预览。它工作正常。我的代码是

string filename = Path.GetFileName(FileUpload1.FileName);
    FileUpload1.SaveAs(Server.MapPath("~/Publisher/ExcelFiles/") + filename);
    DataSet ds = new DataSet();
    string path = @"~/Publisher/ExcelFiles/" + filename;
    OleDbConnection myCon = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");
    OleDbCommand myComm = new OleDbCommand("select * from [GIRLS$] ", myCon);
    OleDbDataAdapter da = new OleDbDataAdapter(myComm);
    da.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();

但我的问题是 excel 文件的路径,它在 da.Fill(ds) 处给我一个错误;

'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\~\Publisher\ExcelFiles\glist.xls' 不是有效路径。确保路径名拼写正确并且您已连接到文件所在的服务器。excel 文件位于我的网站目录中。如果我将路径更改为,则不会出现此错误

string path= @"D:\Vikas Rana\New folder (4)\glist.xls";

任何帮助将不胜感激。提前致谢。

4

1 回答 1

1

尝试这个

string filename = Path.GetFileName(FileUpload1.FileName);

DataSet ds = new DataSet();
string path = Server.MapPath("~/Publisher/ExcelFiles/" + filename);
        FileUpload1.SaveAs(path);
OleDbConnection myCon = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;
DataSource=" + path + ";Extended Properties=Excel 12.0;");
OleDbCommand myComm = new OleDbCommand("select * from [GIRLS$] ", myCon);
OleDbDataAdapter da = new OleDbDataAdapter(myComm);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();

如果您上传 .xls 文件,请使用此

 Provider=Microsoft.Jet.OLEDB.4.0;Data Source=path(which you prefer);Extended Properties="Excel 8.0;HDR=YES;IMEX=1;"

如果您上传 .xlsx 文件,请使用此

 Provider=Microsoft.ACE.OLEDB.12.0;Data Source=path(which you prefer);Extended Properties="Excel 12.0;HDR=YES;IMEX=1;"

我是说

 OleDbConnection myCon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;
  DataSource=" + path + ";Extended Properties=Excel 8.0;HDR=YES;IMEX=1;");
于 2013-11-13T11:31:44.457 回答