Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从ASP.NET(C#)中的Gridview行更新Excel文件?_C#_Asp.net_Excel_Gridview - Fatal编程技术网

如何从ASP.NET(C#)中的Gridview行更新Excel文件?

如何从ASP.NET(C#)中的Gridview行更新Excel文件?,c#,asp.net,excel,gridview,C#,Asp.net,Excel,Gridview,我正在尝试一个简单的程序。当用户单击该按钮时,TextBox1的值将根据存储的过程运行,返回一个客户ID。该客户ID将在Excel工作表中查找。如果找到,对应行的信息将绑定到Gridview。但是,完成后,我想将该行写入从中提取信息的excel文件的第二页。代码有点混乱,因为我正在尝试一些不同的东西 当前Excel文件已保存,但当前所在的行当然会被覆盖,因此始终只有一行 将数据从Gridview(仅包含一行)更新(或插入)到Excel文件的工作表中,最干净、最简单的方法是什么?基本上,这将一次又

我正在尝试一个简单的程序。当用户单击该按钮时,TextBox1的值将根据存储的过程运行,返回一个客户ID。该客户ID将在Excel工作表中查找。如果找到,对应行的信息将绑定到Gridview。但是,完成后,我想将该行写入从中提取信息的excel文件的第二页。代码有点混乱,因为我正在尝试一些不同的东西

当前Excel文件已保存,但当前所在的行当然会被覆盖,因此始终只有一行

将数据从Gridview(仅包含一行)更新(或插入)到Excel文件的工作表中,最干净、最简单的方法是什么?基本上,这将一次又一次地进行(当用户输入一个数字并单击事件按钮时),因此第二张图纸(Sheet2)中的行将从Gridview不断更新。感谢您的帮助。如果这听起来/看起来很业余,我道歉

    protected void Button1_Click(object sender, EventArgs e)
    {

        if (TextBox1.Text != "")
        {

            DateTime saveNow = DateTime.Now;
            long numCardNumber;
            string strCardNumber; // Card number (stored as string)
            char[] MyChar = { ';', '?' }; // array with 2 char
            string customerID; //holds the customer ID returned by the stored proc CNBID
            int CustID = 0; //Customer_id returned from stored proc CNBID
            int incrementByOne; //Used to increment number of cards scanned Application level variable

            //Create local label and assign text -> Site.Master lblTimeStamp
            Label lblTimeStampLocal = (Label)Master.FindControl("lblTimeStamp");
            Label lblScannedLocal = (Label)Master.FindControl("lblScanned");

            //Cleanup input
            strCardNumber = TextBox1.Text.TrimEnd(MyChar); // Trims end
            strCardNumber = strCardNumber.TrimStart(MyChar); //Trims beginning

            lbliMAG.Text = strCardNumber;

            lblYourNumber.Visible = false; //if previously displayed, turns the label off


            try //try and convert the string to a number (if valid numerical characters
            {
                numCardNumber = Convert.ToInt64(strCardNumber);                                                         
            }
            catch (FormatException) // thrown if input characters are not valid numeric
            {
                lblYourNumber.Visible = true;
                GridView1.Visible = false;
                lblQualify.Visible = false;
                lblYourNumber.Text = "NOT A VALID CARD NUMBER!";
                TextBox1.Focus();
                return;
            }

            try //try and convert the string to a number (if valid numerical characters
            {

                string connectionInfo = Convert.ToString(ConfigurationManager.ConnectionStrings["SQLConn"]);
                SqlConnection connection = new SqlConnection(connectionInfo);                   
                connection.Open();

                SqlCommand cmd = new SqlCommand("CNBID", connection);
                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter param = cmd.Parameters.Add("@iMAG", SqlDbType.Char, 18); //@iMAG parameter
                param.Direction = ParameterDirection.Input;
                param.Value = strCardNumber; //Sets the parameter to the value of the scanned card (after trimmed characters)

                try
                {                                      
                    CustID = (int)cmd.ExecuteScalar(); //returns int to customerID if card # found
                }
                catch
                {
                    lblYourNumber.Visible = true;
                    GridView1.Visible = false;
                    lblQualify.Visible = false;
                    lblYourNumber.Text = "NOT A VALID CARD NUMBER!";
                    TextBox1.Focus();
                    return;
                }

                TextBox1.Text = ""; //resets TextBox1; 

                connection.Close();
            }
            catch (FormatException) // thrown if input characters are not valid numeric
            {
                lblYourNumber.Visible = true;
                GridView1.Visible = false;
                lblQualify.Visible = false;
                lblYourNumber.Text = "NOT A VALID CARD NUMBER!";
                TextBox1.Focus();
                return;
            }

            //if (customerID != null)
            if (CustID != 0)
            {

                lblCustID.Text = Convert.ToString(CustID); //assigns customerID to stat label
            }
            else
            {
                lblYourNumber.Visible = true;
                GridView1.Visible = false;
                lblQualify.Visible = false;
                lblYourNumber.Text = "Customer Not Found!";
            }

            //string connString = ConfigurationManager.ConnectionStrings["xls"].ConnectionString;
            string Excel = Server.MapPath("App_Data\\CNB.xls");
            string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Excel + ";Extended Properties=Excel 8.0;";

            //txtReturn.Text = connString; (//shows the connection string

            // Create the connection object
            OleDbConnection oledbConn = new OleDbConnection(connString);
            try
            {
                // Open connection
                oledbConn.Open();

                // Create OleDbCommand object and select data from worksheet Sheet1
                string ExcelConn = "SELECT custid,first,last,addr1,addr2,city,state,zip FROM [Sheet1$] WHERE custid=" + CustID;

                OleDbCommand cmd2 = new OleDbCommand(ExcelConn, oledbConn);

                // Create new OleDbDataAdapter
                OleDbDataAdapter oleda = new OleDbDataAdapter(); //OleDbDataAdapter.SelectCommand

                oleda.SelectCommand = cmd2;

                // Create a DataSet which will hold the data extracted from the worksheet.
                DataSet ds = new DataSet();

                //DataTable dt = new DataTable();

                // Fill the DataSet from the data extracted from the worksheet.
                oleda.Fill(ds, "Processed Customer");

                if (ds.Tables[0].Rows.Count != 0)
                {                       
                    // Bind the data to the GridView                    
                    lblCol1.Text = ds.Tables[0].Columns[0].ColumnName;
                    GridView1.DataSource = ds.Tables[0].Columns[0].ColumnName = " Customer ID ";
                    GridView1.DataSource = ds.Tables[0].Columns[1].ColumnName = " First Name ";
                    GridView1.DataSource = ds.Tables[0].Columns[2].ColumnName = " Last Name ";
                    GridView1.DataSource = ds.Tables[0].Columns[3].ColumnName = " Address 1 ";
                    GridView1.DataSource = ds.Tables[0].Columns[4].ColumnName = " Address 2 ";
                    GridView1.DataSource = ds.Tables[0].Columns[5].ColumnName = " City ";
                    GridView1.DataSource = ds.Tables[0].Columns[6].ColumnName = " Province / State ";
                    GridView1.DataSource = ds.Tables[0].Columns[7].ColumnName = " Postal Code / Zip ";

                    GridView1.DataSource = ds.Tables[0].DefaultView;
                    GridView1.DataBind();

                    GridView1.Visible = true; // SHows the GridView after it populates
                    lblQualify.Visible = true;
                    lblQualify.Text = "Customer Qualifies!";
                    TextBox1.Focus();

                    incrementByOne = (int)Application["numberofTimesScanned"] + 1;
                    Application["numberofTimesScanned"] = incrementByOne;

                    lblTimeStampLocal.Text = "Last Scan: " + Convert.ToString(saveNow);
                    lblScannedLocal.Text = "Number Of Scans Completed: " + Convert.ToString(Application["numberofTimesScanned"]);


                    // Saves Excel document
                    var wb = new XLWorkbook();                    
                    wb.Worksheets.Add(ds);
                    wb.SaveAs(Server.MapPath("App_Data\\CustomersProcessed.xlsx"));

                    TextBox1.Focus();

                    try
                    {
                        cmd2 = new OleDbCommand("INSERT INTO [Sheet2$] (CustID, FirstName) VALUES ('1123', 'Homer')", oledbConn);                            
                        oleda.InsertCommand = cmd2;
                    }
                    catch (Exception error)
                    {
                        lblYourNumber.Text = error.Message;
                    }

                }
                else
                {
                    lblQualify.Text = "Customer Does Not Qualify!";
                    GridView1.Visible = false; // Hides the Gridview 
                    TextBox1.Focus();
                }
            }
            catch (Exception error)
            {
                lblYourNumber.Visible = true;
                GridView1.Visible = false;
                lblQualify.Visible = false;
                lblYourNumber.Text = error.Message;

            }
            finally
            {
                // Close connection
                oledbConn.Close();
            }

        } //END IF
        else
        {
            lblYourNumber.Visible = true;
            lblYourNumber.Text = "NO CARD NUMBER SUBMITTED!";
        }
    }

我最终只使用了以下内容:

using (DbCommand command = oledbConn.CreateCommand())
{
    command.CommandText = "INSERT INTO [Sheet2$] (custid, Fullname, Salutation) VALUES (" + CustID + ",\"John Smith\",\"John\")";

    //connection.Open();

    command.ExecuteNonQuery();
}

成功了。:-)

您的excel是否必须采用.xls格式?操作.xlsx文件要容易得多。有几个不错的.net库。不,绝对可以是.xlsx格式。这是一个很好的观点,谢谢Emmanuel。试试看,一个读写.xlsx文件的很好的库