c# - 如何从自动生成 gridview 列的 excel 中保存我的数据?

标签 c# asp.net database excel gridview

我知道这可能是一个重复的问题,但我无法在任何地方找到它。

我正在将数据从 excel 导入到 gridview,但如何将 gridview 数据保存到数据库中,并且 gridview 中的列是自动生成的。 数据已经反射(reflect)在gridview中,如何保存到数据库中?

如果有人能教我如何在不使用 gridview 作为媒介的情况下直接从 excel 插入到数据库,那就更好了。(尝试使用 this 但一直告诉我 excel 工作表不存在)。

绑定(bind) GridView 的代码:

  string conStr = "";
    switch (Extension)
    {
        case ".xls": //Excel 97-03
            conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"]
                     .ConnectionString;
            break;
        case ".xlsx": //Excel 07
            conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"]
                      .ConnectionString;
            break;
    }
    conStr = String.Format(conStr, FilePath, isHDR);
    OleDbConnection connExcel = new OleDbConnection(conStr);
    OleDbCommand cmdExcel = new OleDbCommand();
    OleDbDataAdapter oda = new OleDbDataAdapter();
    DataTable dt = new DataTable();
    cmdExcel.Connection = connExcel;

    //Get the name of First Sheet
    connExcel.Open();
    DataTable dtExcelSchema;
    dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
    string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();


    connExcel.Close();

    //Read Data from First Sheet
    connExcel.Open();
    cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
    oda.SelectCommand = cmdExcel;
    oda.Fill(dt);
    connExcel.Close();

    //Bind Data to GridView

    GridView1.Caption = Path.GetFileName(FilePath);
    GridView1.DataSource = dt;
    GridView1.DataBind();

是的,我正在使用来自 aspsnippets 的代码。

最佳答案

我最近做了这个,但我只为文件类型 Microsoft Office Excel Worksheet (.xlsx) 做了。首先,您必须将 excel 文件复制到您的应用程序目录,然后将数据保存到 DataTable,最后将其绑定(bind)到 Gridview

使用这些命名空间

using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;

这是方法

private void Import_To_GridTest(string FilePath)
        {
            DataTable dt =new DataTable();

            try
            {
                string sSheetName = null;
                string sConnection = null;
                DataTable dtTablesList = default(DataTable);
                OleDbDataAdapter oda = new OleDbDataAdapter();
                OleDbConnection oleExcelConnection = default(OleDbConnection);
                sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Macro;HDR=YES;IMEX=1\"";
                sConnection = String.Format(sConnection, FilePath);
                oleExcelConnection = new OleDbConnection(sConnection);
                oleExcelConnection.Open();
                dtTablesList = oleExcelConnection.GetSchema("Tables");
                if (dtTablesList.Rows.Count > 0)
                {
                    sSheetName = dtTablesList.Rows[0]["TABLE_NAME"].ToString();
                }
                dtTablesList.Clear();
                dtTablesList.Dispose();

                if (!string.IsNullOrEmpty(sSheetName))
                {
                    var oleExcelCommand = oleExcelConnection.CreateCommand();
                    oleExcelCommand.CommandText = "Select * From [" + sSheetName + "]";
                    oleExcelCommand.CommandType = CommandType.Text;
                    oda.SelectCommand = oleExcelCommand;
                    oda.Fill(dt);
                    oleExcelConnection.Close();
                }

                oleExcelConnection.Close();

                gridview1.DataSource = dt;
                gridview1.DataBind();



            }

            catch (Exception e)
            {
                lblMsg.Text = "Unspecified Error Occured..!! <br>" + e.Message;
                divMsg.Attributes["class"] = "alert alert-danger";
                mainDiv.Visible = true;
                File.Delete(FilePath);

            }
        }

最后提交按钮点击事件

 protected void btnsubmit_OnClick(object sender, EventArgs e)
        {
            if (fileUpload1.HasFiles)
            {
                string FileName = Path.GetFileName(fileUpload1.PostedFile.FileName);
                string FolderPath = "Excels/"; // your path 
                string FilePath = Server.MapPath(FolderPath + DateTime.Now.ToString("ddmmyyhhmmss") + FileName);
                // copy and save the the excel
                fileUpload1.SaveAs(FilePath);
                Import_To_GridTest(FilePath);
            }
        }

更新:用于将数据保存到数据库使用SqlBulkCopy

private void SqlbulkCopy(DataTable dt)
        {

            if (dt.Rows.Count > 0)
            {
                string consString = ConfigurationManager.ConnectionStrings["Bulkcopy"].ConnectionString;
                using (SqlConnection con = new SqlConnection(consString))
                {
                    using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
                    {
                        //Set the database table name
                        sqlBulkCopy.DestinationTableName = "dbo.leads";

                        //[OPTIONAL]: Map the DataTable columns with that of the database table

                        sqlBulkCopy.ColumnMappings.Add("Currunt_Company", "CuCompany");
                        sqlBulkCopy.ColumnMappings.Add("Currunt_Product", "CuProduct");
                        sqlBulkCopy.ColumnMappings.Add("Quantity", "Quantity");
                        sqlBulkCopy.ColumnMappings.Add("Unit_Price", "UnitPrice");
                        sqlBulkCopy.ColumnMappings.Add("Total_Price", "TotalPrice");
                        sqlBulkCopy.ColumnMappings.Add("Contect_Person", "ContectPerson");

                        con.Open();
                        sqlBulkCopy.WriteToServer(dt);
                        con.Close();
                    }
                }
            }
        }

关于c# - 如何从自动生成 gridview 列的 excel 中保存我的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37716781/

相关文章:

php - [已死]如何使用异步回发成功发布到旧的 ASP.NET 站点

java - 在数据库中创建空对象或稍后保存

javascript - Angular/C# CORS 问题

c# - 公共(public)访问器与类的公共(public)属性

c# - 舍入浮点值

c# - 将值从 Controller 发送到 Jquery

新线程中的 C# 计时器

c# - ASP.NET 以强类型方式引用图像或 asp 文件

database - 将联系表格 7 数据保存到自定义数据库而不是 wordpress 数据库中

sql - 同一张表的一对多关系