Как обновить файл Excel из строки Gridview в ASP.NET (C #)? - PullRequest
0 голосов
/ 01 ноября 2011

Я пытаюсь выполнить простую программу. Когда пользователь нажимает кнопку, значение TextBox1 запускается для сохраненного процесса, возвращая идентификатор клиента. Этот идентификатор клиента ищется в листе 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!";
        }
    }

1 Ответ

1 голос
/ 02 ноября 2011

В итоге я использовал следующее:

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

    //connection.Open();

    command.ExecuteNonQuery();
}

Вот и все.: -)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...