Microsoft Office Access数据库引擎无法打开或写入文件“

数据需要从Excel工作表中读入.net gridview。 这里是aspx和aspx.cs代码。

ASPX:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Read and Display Data From an Excel File (.xsl or .xlsx) in ASP.NET</title> </head> <body> <form id="form1" runat="server"> <div> <b>Please Select Excel File: </b> <asp:FileUpload ID="fileuploadExcel" runat="server" />&nbsp;&nbsp; <asp:Button ID="btnImport" runat="server" Text="Import Data" OnClick="btnImport_Click" /> <br /> <asp:Label ID="lblMessage" runat="server" Visible="False" Font-Bold="True" ForeColor="#009933"></asp:Label><br /> <asp:GridView ID="grvExcelData" runat="server"> <HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" /> </asp:GridView> </div> </form> </body> </html> 

ASPX.CS

 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.OleDb; using System.IO; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnImport_Click(object sender, EventArgs e) { string connString = ""; string strFileType = Path.GetExtension(fileuploadExcel.FileName).ToLower(); string path = fileuploadExcel.PostedFile.FileName; //Connection String to Excel Workbook if (strFileType.Trim() == ".xls") { connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""; } else if (strFileType.Trim() == ".xlsx") { connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path +";Extended Properties=\"Excel 12.0 Xml;HDR=Yes;IMEX=2;\""; } string query = "SELECT [UserName],[Education],[Location] FROM [Sheet1$]"; OleDbConnection conn = new OleDbConnection(connString); conn.Open(); OleDbCommand cmd = new OleDbCommand(query, conn); OleDbDataAdapter da = new OleDbDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); grvExcelData.DataSource = ds.Tables[0]; grvExcelData.DataBind(); da.Dispose(); conn.Close(); conn.Dispose(); } 

conn.Open(); 给出以下错误:

Microsoft Office Access数据库引擎无法打开或写入文件“”。 它已经由另一个用户专门打开,或者您需要查看和写入其数据的权限。

networking服务已经提供了存储Excel工作表的文件夹的所有权限。

尝试处理之前,使用FileUpload.SaveAs将上传的文件保存到磁盘位置。 正如文件警告,

FileUpload控件不会自动将文件保存到服务器…

文件caching在内存或磁盘上的临时文件夹,直到您保存它们。

您应该考虑使用不同的Excel文件处理方法,如EPPlus (用于xlsx), NPOI (xls和xlsx)或者仅用于开放XML SDK(xlsx)。 他们不需要Jet驱动程序,更less的怪癖和一些可以直接读取stream。

这将允许您直接从上传文件的InputStream属性中读取上传的内容。 例如,使用Open XML SDK ,您可以编写:

 using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(fileuploadExcel.PostedFile.InputStream, false)) { ... }