我正在使用以下代码将Excel文件数据导入到Grid视图中。但是我遇到了错误。
protected void uploadLinkButton_Click(object sender, EventArgs e)
{
string name = "Items";
string path = Server.MapPath(StyleOperationsFileUpload.FileName);
string Constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=2;'";
OleDbConnection OleCon = new OleDbConnection(Constr);
OleDbCommand OleCom = new OleDbCommand("Select * From [" + name + "$]", OleCon);
OleCon.Open();
OleDbDataAdapter OleAdapObj = new OleDbDataAdapter(OleCom);
DataTable DatTabObj = new DataTable();
OleAdap.Fill(DatTab);
UploadGridView.DataSource = DatTab;
UploadGridView.DataBind();
}
错误如下
Microsoft Access数据库引擎找不到对象 “ Items $”。确保该对象存在,并拼写其名称,然后 正确的路径名。如果“ Items $”不是本地对象,请检查您的 网络连接或与服务器管理员联系。
完整的堆栈跟踪和错误如下
System.Data.OleDb.OleDbException was unhandled by user code
ErrorCode=-2147217865
HResult=-2147217865
Message=The Microsoft Access database engine could not find the object 'Items$'. Make sure the object exists and that you spell its name and the path name correctly. If 'Items$' is not a local object, check your network connection or contact the server administrator.
Source=Microsoft Access Database Engine
StackTrace:
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.OleDb.OleDbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
at StyleOperations.Operations.uploadLinkButton_Click(Object sender, EventArgs e) in D:\Developments\On Going Developments\StyleOperations\StyleOperations\StyleOperations\Operations.aspx.cs:line 145
at System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e)
at System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
请帮助我解决此问题。先感谢您。
下面是excel文件的格式。 Excel文件的名称为 Sheet1
| 1 |DESCRIPTION| SMV |SEQ NO
| 2 | Des1 | 1.2 | 1
| 3 | Des2 | 2.5 | 2
| 4 | Des3 | 5.8 | 3
| 5 | Des4 | 4.2 | 4
答案 0 :(得分:1)
只需确保,我们或多或少都在同一页面上。
我修复了一些错误,但无论如何这都会阻止您。
// The name of the EXCEL-SHEET in the Excel File.
string name = "Items$";
// The Pathname of the Excel File
string path = Server.MapPath(StyleOperationsFileUpload.FileName);
// Getting the Extension to check whether it's old or new Office file.
string Extension = Path.GetExtension(path).ToLower();
// Default ConStr for "new" Excel (> 2003)
string ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=2'";
if (Extension.Trim() == ".xls")
{
// ConStr for old Excel 97-2003 Project
ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=2'";
}
OleDbConnection OleCon = new OleDbConnection(ConStr);
if (OleCon.State == ConnectionState.Closed)
{
OleCon.Open();
}
// It seems that there might be some confusion about what that Sheet is called, so I would suggest checking up on what's in there..
bool doThatThing = false;
DataTable xTables = OleCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow xTable in xTables.Rows)
{
// SheetsInFile:
//sheetsInFile.Text += xTable["TABLE_NAME"].ToString();
if (name == xTable["TABLE_NAME"].ToString())
doThatThing = true;
}
if (doThatThing)
{
OleDbCommand OleCom = new OleDbCommand("Select * From [" + name + "]", OleCon);
OleDbDataAdapter OleAdapObj = new OleDbDataAdapter(OleCom);
DataTable DatTabObj = new DataTable();
OleAdapObj.Fill(DatTabObj);
UploadGridView.DataSource = DatTabObj;
UploadGridView.DataBind();
}
// Don't forget to close Connection
OleCon.Close();
也许将其添加到您的前面,并在后面的代码中包含sheetsInFile。
<asp:Label ID="sheetsInFile" runat="server"></asp:Label>
---编辑---
现在,您已经对Folderpath进行了排序,它可能适用于此。
string ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Folderpath + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=2'";
if (Extension.Trim() == ".xls")
{
// ConStr for Excel 97-2003 Project
ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Folderpath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=2'";
}
OleDbConnection OleCon = new OleDbConnection(ConStr);
if (OleCon.State == ConnectionState.Closed)
{
OleCon.Open();
}
// If you know there is only going to be one Sheet
// - with a variable name, that you can't rememeber...
name = OleCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
OleDbCommand OleCom = new OleDbCommand("Select * From [" + name + "]", OleCon);
OleDbDataAdapter OleAdapObj = new OleDbDataAdapter(OleCom);
DataTable DatTabObj = new DataTable();
OleAdapObj.Fill(DatTabObj);
UploadGridView.DataSource = DatTabObj;
UploadGridView.DataBind();
答案 1 :(得分:0)
无论如何,我找到了答案。 @JanAndersen谢谢您的帮助。下面是我的代码。现在工作正常。 :)
using ClosedXML.Excel;
protected void uploadLinkButton_Click(object sender, EventArgs e)
{
try
{
string FileName = Path.GetFileName(StyleOperationsFileUpload.PostedFile.FileName);
string FolderPath = Server.MapPath("~/Downloads/" + FileName);
StyleOperationsFileUpload.SaveAs(FolderPath);
using (XLWorkbook workbook = new XLWorkbook(FolderPath))
{
IXLWorksheet worksheet = workbook.Worksheet(1);
DataTable DatTab = new DataTable();
bool FirstRow = true;
foreach (IXLRow row in worksheet.Rows())
{
if (FirstRow)
{
foreach (IXLCell cell in row.Cells())
{
DatTab.Columns.Add(cell.Value.ToString());
}
FirstRow = false;
}
else
{
DatTab.Rows.Add();
int i = 0;
foreach (IXLCell cell in row.Cells())
{
DatTab.Rows[DatTab.Rows.Count - 1][i] = cell.Value.ToString();
i++;
}
}
}
UploadGridView.DataSource = DatTab;
UploadGridView.DataBind();
}
SaveLinkButton.Enabled = true;
}
catch (Exception ex)
{
Response.Write("<script>alert('Please Restart the system: " + ex + "')</script>");
}
}