将Excel文件导入网格视图时出错
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将Excel文件导入网格视图时出错相关的知识,希望对你有一定的参考价值。
我使用下面的代码将Excel文件数据导入网格视图。但是我收到了一个错误。
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:DevelopmentsOn Going DevelopmentsStyleOperationsStyleOperationsStyleOperationsOperations.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
答案
只是确定,我们在这里,呃,或多或少都在同一页面上。
我修复了一些错误,无论如何都会阻止你。
// 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();
另一答案
无论如何,我找到了答案。 @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>");
}
}
以上是关于将Excel文件导入网格视图时出错的主要内容,如果未能解决你的问题,请参考以下文章
通过 Aginity Workbench for Netezza 导入 excel 文件时出错
SQL Server 2005导入数据时出错,导入的是TXT文本格式