如何将新列附加到数据表并填充它?

时间:2016-03-10 07:55:12

标签: c# asp.net excel gridview

我有一张excel表,包含4个字段和10个记录。我将它们导入到数据表中,使用SQLBulkCopy将其绑定到已创建的名为“SampleTable”的数据库表,获取从SampleTable存储的数据并将其绑定到DataGridView以供显示。而且......我知道这是一个全面的过程。

此时我只需要澄清......

标记

<asp:Label ID="sampleText" runat="server" Text="Upload the Excel Sheet"/><br /><br />
    <asp:FileUpload ID="FileUpload1" runat="server" /><br /><br />
    <asp:Button ID="uploadClick" runat="server" Text="Upload" OnClick="uploadClick_Click" />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
        <Columns>

        </Columns>
    </asp:GridView>

代码背后

using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Configuration;

public partial class Pages_Default3 : System.Web.UI.Page
{
    //region constants
    const string Gender = "Gender";
    //end region

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void uploadClick_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            try
            {
                //Upload and save the file
                string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
                string fileLocation = Server.MapPath("~/App_Data/" + fileName);
                FileUpload1.SaveAs(fileLocation);

                string conString = string.Empty;
                string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                switch (extension)
                {
                    case ".xls": //Excel 97-03
                        conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                        break;
                    case ".xlsx": //Excel 07 or higher
                        conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
                        break;

                }
                conString = string.Format(conString, fileLocation);
                using (OleDbConnection excel_con = new OleDbConnection(conString))
                {
                    excel_con.Open();
                    string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
                    DataTable dtExcelData = new DataTable();

                    dtExcelData.Columns.AddRange(new DataColumn[4] { new DataColumn("ID", typeof(int)), new DataColumn("Name", typeof(string)), new DataColumn("City", typeof(string)), new DataColumn("State", typeof(string)) });

                    using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT [ID], [Name], [City], [State] FROM [" + sheet1 + "]", excel_con))
                    {
                        oda.Fill(dtExcelData);


                        {


                        }
                    }


                    excel_con.Close();

                    string consString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                    using (SqlConnection con = new SqlConnection(consString))
                    {
                        using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
                        {
                            //Set the database table name
                            sqlBulkCopy.DestinationTableName = "dbo.SampleTable";

                            //[OPTIONAL]: Map the Excel columns with that of the database table
                            sqlBulkCopy.ColumnMappings.Add("ID", "ID");
                            sqlBulkCopy.ColumnMappings.Add("Name", "Name");
                            sqlBulkCopy.ColumnMappings.Add("City", "City");
                            sqlBulkCopy.ColumnMappings.Add("State", "State");
                            con.Open();
                            sqlBulkCopy.WriteToServer(dtExcelData);
                            con.Close();
                            string message = "<script type='javascript'> prompt('Upload Complete');</script>";
                            Response.Write(message);
                            BindGrid();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex);
            }
        }
    }

    protected void BindGrid()
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT [ID], [Name], [City], [State] FROM SampleTable"))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);
                        GridView1.DataSource = dt;
                        GridView1.DataBind();
                    }
                }
            }
        }
    }
}
  • 我想在 gridview 上添加一个名为性别的额外列,并有2个单选按钮,即“男性”和“ 女性'在ID为偶数的每一行上。

  • 标记/选中的单选按钮的值应反过来反映在数据库表中。

  

注意:我有6个字段[含税]已经创建的性别(允许空)]   数据库表,我只需要用值填充空值   分配给gridview中的单选按钮。

0 个答案:

没有答案