C#System.Data.OleDb.OleDbException错误

时间:2016-02-16 20:55:30

标签: c# asp.net

我在c#中的代码有问题。对不起,新手。我想要导入和导出数据到数据库。当我导入* .xlsx时,我有comunique:

  

异常类型“System.Data.OleDb.OleDbException”ASP导出Import.dll,但未在用户代码中处理   附加信息:字符串“EmployeeData $”不是有效名称

Deafult.aspx.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ASPExportImport
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PopulateData();
                lblMessage.Text = "Current Database Data!";
            }
        }
        private void PopulateData()
        {
            using (MuDatabaseEntities dc = new MuDatabaseEntities())
            {
                gvData.DataSource = dc.EmployeeMaster.ToList();
                gvData.DataBind();
            }
        }
        protected void btnImport_Click(object sender, EventArgs e)
        {
            if (FileUpload1.PostedFile.ContentType == "application/vnd.ms-excel" ||
                FileUpload1.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                try
                {
                    string fileName = Path.Combine(Server.MapPath("~/ImportDocument"), Guid.NewGuid().ToString() + Path.GetExtension(FileUpload1.PostedFile.FileName));
                    FileUpload1.PostedFile.SaveAs(fileName);

                    string conString = "";
                    string ext = Path.GetExtension(FileUpload1.PostedFile.FileName);
                    if (ext.ToLower() == ".xls")
                    {
                        conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""; ;
                    }
                    else if (ext.ToLower() == ".xlsx")
                    {
                        conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                    }

                    string query = "Select [EmployeeID],[CompanyName], [ContactName],[ContactTitle],[EmployeeAdress],[PostalCode] from [EmployeeData$]";
                    OleDbConnection con = new OleDbConnection(conString);
                    if (con.State == ConnectionState.Closed)
                    {
                        con.Open();
                    }
                    OleDbCommand cmd = new OleDbCommand(query, con);
                    OleDbDataAdapter da = new OleDbDataAdapter(cmd);

                    DataSet ds = new DataSet();
                    da.Fill(ds);
                    da.Dispose();
                    con.Close();
                    con.Dispose();

                    // Import to Database
                    using (MuDatabaseEntities dc = new MuDatabaseEntities())
                    {
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            string empID = dr["EmployeeID"].ToString();
                            var v = dc.EmployeeMaster.Where(a => a.EmployeeID.Equals(empID)).FirstOrDefault();
                            if (v != null)
                            {
                                // Update here
                                v.CompanyName = dr["CompanyName"].ToString();
                                v.ContactName = dr["ContactName"].ToString();
                                v.ContactTitle = dr["ContactTitle"].ToString();
                                v.EmployeeAdress = dr["EmployeeAdress"].ToString();
                                v.PostalCode = dr["PostalCode"].ToString();
                            }
                            else
                            {
                                // Insert
                                dc.EmployeeMaster.Add(new EmployeeMaster
                                {
                                    EmployeeID = dr["EmployeeID"].ToString(),
                                    CompanyName = dr["CompanyName"].ToString(),
                                    ContactName = dr["ContactName"].ToString(),
                                    ContactTitle = dr["ContactTitle"].ToString(),
                                    EmployeeAdress = dr["EmployeeAdress"].ToString(),
                                    PostalCode = dr["PostalCode"].ToString()
                                });
                            }
                        }

                        dc.SaveChanges();
                    }

                    PopulateData();
                    lblMessage.Text = "Successfully data import done!";
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
        protected void btnExport_Click(object sender, EventArgs e)
        {
            using (MuDatabaseEntities dc = new MuDatabaseEntities())
            {
                List<EmployeeMaster> emList = dc.EmployeeMaster.ToList();
                StringBuilder sb = new StringBuilder();

                if (emList.Count > 0)
                {
                    string fileName = Path.Combine(Server.MapPath("~/ImportDocument"), DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xlsx");
                    string conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0 Xml;HDR=Yes'";
                    using (OleDbConnection con = new OleDbConnection(conString))
                    {
                        string strCreateTab = "Create table EmployeeData (" +
                            " [Employee ID] varchar(50), " +
                            " [Company Name] varchar(200), " +
                            " [Contact Name] varchar(200), " +
                            " [Contact Title] varchar(200), " +
                            " [Employee Address] varchar(200), " +
                            " [Postal Code] varchar(50))";
                        if (con.State == ConnectionState.Closed)
                        {
                            con.Open();
                        }

                        OleDbCommand cmd = new OleDbCommand(strCreateTab, con);
                        cmd.ExecuteNonQuery();

                        string strInsert = "Insert into EmployeeData([Employee ID],[Company Name]," +
                            " [Contact Name], [Contact Title], [Employee Address], [Postal Code]" +
                            ") values(?,?,?,?,?,?)";
                        OleDbCommand cmdIns = new OleDbCommand(strInsert, con);
                        cmdIns.Parameters.Add("?", OleDbType.VarChar, 50);
                        cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
                        cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
                        cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
                        cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
                        cmdIns.Parameters.Add("?", OleDbType.VarChar, 50);

                        foreach (var i in emList)
                        {
                            cmdIns.Parameters[0].Value = i.EmployeeID;
                            cmdIns.Parameters[1].Value = i.CompanyName;
                            cmdIns.Parameters[2].Value = i.ContactName;
                            cmdIns.Parameters[3].Value = i.ContactTitle;
                            cmdIns.Parameters[4].Value = i.EmployeeAdress;
                            cmdIns.Parameters[5].Value = i.PostalCode;

                            cmdIns.ExecuteNonQuery();
                        }
                    }

                    // Create Downloadable file
                    byte[] content = File.ReadAllBytes(fileName);
                    HttpContext context = HttpContext.Current;

                    context.Response.BinaryWrite(content);
                    context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    context.Response.AppendHeader("Content-Disposition", "attachment; filename=EmployeeData.xlsx");
                    Context.Response.End();
                }
            }
        }
    }
}

Deafult.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ASPExportImport._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

 
        <h3>Import / Export database data from/to Excel.</h3>
    <div>
        <table>
            <tr>
                <td>Select File : </td>
                <td>
                    <asp:FileUpload ID="FileUpload1" runat="server" />
                    </td>
                <td>
                    <asp:Button ID="btnImport" runat="server" Text="Import Data" OnClick="btnImport_Click" />
                </td>
            </tr>
        </table>
        <div>
            <br />
            <asp:Label ID="lblMessage" runat="server"  Font-Bold="true" />
            <br />
            <asp:GridView ID="gvData" runat="server" AutoGenerateColumns="false">
                <EmptyDataTemplate>
                    <div style="padding:10px">
                        Data not found!
                    </div>
                </EmptyDataTemplate>
                <Columns>
                    <asp:BoundField HeaderText="EmployeeID" DataField="EmployeeID" />
                    <asp:BoundField HeaderText="CompanyName" DataField="CompanyName" />
                    <asp:BoundField HeaderText="ContactName" DataField="ContactName" />
                    <asp:BoundField HeaderText="ContactTitle" DataField="ContactTitle" />
                    <asp:BoundField HeaderText="Address" DataField="EmployeeAddress" />
                    <asp:BoundField HeaderText="PostalCode" DataField="PostalCode" />
                </Columns>
            </asp:GridView>
            <br />
            <asp:Button ID="btnExport" runat="server" Text="Export Data" OnClick="btnExport_Click" />
        </div>
    </div>

</asp:Content>

要导入的示例文件: http://185.5.99.98/EmployeeData.xlsx

FullProject: http://185.5.99.98/ASPExportImport.zip

所有答案的答案......

2 个答案:

答案 0 :(得分:0)

append

您似乎正在尝试从无效的表名中提取数据。在上面列出的代码段中,$ sign是否有意?

假设您尝试从表名EmployeeData而不是EmployeeData $中提取数据,请更改要使用的SQL查询:

score_list

<强> 修改 我下载了示例文件,并手动将它们剪切成一个新项目来测试您的例程。似乎代码本身工作得很好。我能够毫无问题地访问excel电子表格。请查看您的Excel电子表格以了解拼写错误。我注意到在您的示例电子表格中有很多错误会导致查询崩溃。具体来说,请验证电子表格中的选项卡是否已命名为EmployeeData。此外,验证所有列标题拼写。

以下代码段没有任何问题,应该包含阅读Excel电子表格的核心功能。

string query = "Select [EmployeeID],[CompanyName], [ContactName],[ContactTitle],[EmployeeAdress],[PostalCode] from [EmployeeData$]";

答案 1 :(得分:0)

嗨朋友请回答...... 我在html中搜索:

&#13;
&#13;
<asp:BoundField HeaderText="Address" DataField="EmployeeAddress" />
&#13;
&#13;
&#13;

必须是

&#13;
&#13;
<asp:BoundField HeaderText="Address" DataField="EmployeeAdress" />
&#13;
&#13;
&#13;

我知道Adress是错误的词;)抱歉我的英语;)

在工作表中是

  

Emloyee ID

必须是

  

员工ID

效果很好;)谢谢大家。