如何从excel中保存我自己生成gridview列的数据?

时间:2016-06-09 04:22:34

标签: c# asp.net database excel gridview

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

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

如果有人可以教我如何直接从excel插入到数据库而不使用gridview作为媒介,那会更好。(尝试使用this但是一直告诉我excel表不存在)。

绑定网格视图的代码:

  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的代码。

1 个答案:

答案 0 :(得分:1)

我最近这样做了,但我只为fileType Microsoft Office Excel Worksheet (.xlsx)做了这件事。首先,您必须将excel文件复制到Application目录,然后将数据保存到DataTable,最后将其绑定到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);

            }
        }

最后提交按钮Click事件

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