【问题标题】:Error when importing Excel file to grid view将 Excel 文件导入网格视图时出错
【发布时间】:2019-02-05 03:12:57
【问题描述】:

我正在使用以下代码将 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$' 不是本地对象,请检查您的 网络连接或联系服务器管理员。

完整的堆栈跟踪和错误如下

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

【问题讨论】:

  • 缺少什么? excel长什么样子?
  • @JanAndersen 我已经编辑了问题并添加了 Excel 文件的格式。请看一下。
  • 您是否将默认 sheet1 重命名为 Items 或为 Item 创建了新工作表?
  • ^ 因为,否则您需要将分配给 name 的值更改为: string name = "Sheet1";
  • 不,我正在将代码中的名称 Sheet1 修改为 Items。即使我没有修改名称,我也遇到了同样的错误。只是名称 Item 已错误地替换为 Sheet1 :D

标签: c# excel gridview import


【解决方案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();

也许将其添加到您的前面,并将 sheetInFile 包含在代码隐藏中。

<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();

【讨论】:

  • 嗨@JanAnderson,抱歉耽搁了。我尝试过这个。代码一直执行到foreach,没有任何错误。在foreach 中,首先跳转到xTables.rows,然后跳转到in,然后直接跳转到if (doThatThing)。由于bool 设置为false,因此不会检查子句并且不会读取excel 文件。
  • 那么我建议您删除 sheetInFile 上的双斜杠并将该标签添加到您的输出页面,这样您就可以了解“项目”的“真实”名称;)
  • 我之前也试过了。但是,foreach 不会被触发,因此无法获取真实的文件名。循环不执行。
  • foreach不是通过文件名,而是通过Excel文件中的Sheet名,如图。您确定您正在处理正确的文件吗?我认为您应该检查您的 StyleOperationsFileUpload.FileName 实际返回的内容。
  • StyleOperationsFileUpload.FileName 返回路径为"D:\\Developments\\On Going Developments\\StyleOperations\\StyleOperations\\StyleOperations\\Operation_Update.xlsx"。哪个是正确的文件路径名。但是foreach 不会循环遍历Operation_Update.xlsx 文件中的工作表。
【解决方案2】:

无论如何,我找到了答案。 @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>");
        }

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多