Microsoft Jet数据库引擎无法打开文件''它已经由另一个用户独占打开,或者您需要权限才能查看其
本文关键字:或者 权限 引擎 数据库 Jet 文件 另一个 Microsoft 用户 | 更新日期: 2023-09-27 18:10:50
我使用OLEDB服务器在我的ASP中读取excel文件。. NET MVC项目。然后我得到了错误"Microsoft Jet数据库引擎无法打开该文件"。它已经由另一个用户独占打开,或者您需要权限才能查看其数据"。相同的代码与不同的CSV文件的连接字符串工作正常,但对于Excel connectionString我得到这个错误。请问有谁知道这个问题的解决办法吗?
我的代码是:public JsonResult ImportCSVFiles()
{
HttpPostedFileBase hpf = null;
foreach (string file in Request.Files)
{
hpf = Request.Files[file] as HttpPostedFileBase;
}
string[] FileName;
string filename = hpf.FileName;
string DestinationPath = Server.MapPath("..") + "''CSVFiles''";
if (!Directory.Exists(DestinationPath))
{
Directory.CreateDirectory(DestinationPath);
if (System.IO.File.Exists(Server.MapPath("..") + "''CSVFiles''" + filename) == false)
{
hpf.SaveAs(DestinationPath + filename);
}
else
{
System.IO.File.Delete(Server.MapPath("..") + "''CSVFiles''" + filename);
hpf.SaveAs(DestinationPath + filename);
}
}
else
{
if (System.IO.File.Exists(Server.MapPath("..") + "''CSVFiles''" + filename) == false)
{
hpf.SaveAs(DestinationPath + filename);
}
else
{
System.IO.File.Delete(Server.MapPath("..") + "''CSVFiles''" + filename);
hpf.SaveAs(DestinationPath + filename);
}
}
bool isFirstRowHeader = true;
string header = isFirstRowHeader ? "Yes" : "No";
string path = "";
string pathOnly = Path.GetDirectoryName(DestinationPath);
string fileName = Path.GetFileName(DestinationPath + "''" + filename);
string sql = @"SELECT * FROM [" + fileName + "]";
//using (OleDbConnection connection = new OleDbConnection(
// @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
// ";Extended Properties='"Text;HDR=" + header + "'""))
using (OleDbConnection connection = new OleDbConnection(
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties='"Excel 8.0;HDR=Yes;IMEX=1'";"))
using (OleDbCommand command = new OleDbCommand(sql, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
}
}
已注释的connectionstring适用于CSV文件,CSV文件在相同的代码下可以正常工作。
我在最近编写的一个程序中遇到了同样的问题。我的解决方案是简单地从连接字符串中取出额外的位。我不知道为什么它有效,但既然它对我有效,它可能对你有用。这就是你的新连接字符串的样子:
using (OleDbConnection connection = new OleDbConnection(
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + ";"))
你可以保留HDR=Yes位因为我知道你可能需要它来告诉它有标题我不认为保留它会影响它