导出的gridview到csv是空的

时间:2014-02-25 13:19:53

标签: c# asp.net .net csv gridview

我想通过点击按钮" RunSimulationButton "将我的Gridview导出到csv文件。但是,我的当前代码似乎只导出列名,但不会导出gridview的单元格内容。

任何帮助将不胜感激!谢谢! (P.S:我是ASP.NET的初学者)

这是我的代码:

ASPX

<asp:GridView ID="InflationGridView" runat="server" AutoGenerateColumns="False" Width="52%"
                                            ShowHeaderWhenEmpty="True" CellPadding="4" ForeColor="#333333" GridLines="None"
                                            AllowSorting="True" ShowFooter="True">
                                            <AlternatingRowStyle BackColor="White" ForeColor="#284775" Height="2px" />
                                            <Columns>
                                                <asp:TemplateField HeaderText="Start Year">
                                                    <ItemStyle Font-Size="13px" Width="20%" HorizontalAlign="Center" />
                                                    <ItemTemplate>
                                                        <asp:TextBox ID="StartInflationTextBox" runat="server" Width="60px" Text="" Style="text-align: center;"></asp:TextBox>
                                                        <asp:NumericUpDownExtender ID="StartInflationNumericUpDownExtender" runat="server"
                                                            TargetControlID="StartInflationTextBox" Minimum="0" Width="60">
                                                        </asp:NumericUpDownExtender>
                                                    </ItemTemplate>
                                                </asp:TemplateField>
                                                <asp:TemplateField HeaderText="End Year">
                                                    <ItemStyle Font-Size="13px" Width="20%" HorizontalAlign="Center" />
                                                    <ItemTemplate>
                                                        <asp:TextBox ID="EndInflationTextBox" runat="server" Width="60px" Text="" Style="text-align: center;"></asp:TextBox>
                                                        <asp:NumericUpDownExtender ID="EndInflationNumericUpDownExtender" runat="server"
                                                            TargetControlID="EndInflationTextBox" Minimum="1" Width="60">
                                                        </asp:NumericUpDownExtender>
                                                    </ItemTemplate>
                                                </asp:TemplateField>
                                                <asp:TemplateField HeaderText="Inflation Rate">
                                                    <ItemStyle Font-Size="13px" Width="25%" HorizontalAlign="Center" Height="2px" />
                                                    <ItemTemplate>
                                                        <asp:TextBox ID="InflationTextBox" runat="server" Text="" Width="60px" Style="text-align: center;"></asp:TextBox>
                                                        %
                                                    </ItemTemplate>
                                                    <FooterStyle HorizontalAlign="Right" />
                                                    <FooterTemplate>
                                                        <asp:Button ID="AddNewInflationRowButton" runat="server" Text="Add New Row" OnClick="AddNewInflationRowButton_Click"
                                                            Height="25px" />
                                                    </FooterTemplate>
                                                </asp:TemplateField>
                                            </Columns>
                                            <FooterStyle Font-Bold="True" ForeColor="White" Height="20px" />
                                            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                                            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                                            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                                            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" Height="10px" />
                                            <SortedAscendingCellStyle BackColor="#E9E7E2" />
                                            <SortedAscendingHeaderStyle BackColor="#506C8C" />
                                            <SortedDescendingCellStyle BackColor="#FFFDF8" />
                                            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                                        </asp:GridView>
<asp:Button ID="RunSimulationButton" runat="server" Text="Run Simulation" OnClick="RunSimulationButton_OnClick" />

ASPX.cs

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            FirstInflationGridViewRow();
        }


    }


    // Display first row of the GridView
    protected void FirstInflationGridViewRow()
    {
        DataTable table = new DataTable();
        DataRow dr = null;

        table.Columns.Add(new DataColumn("Col1", typeof(int)));
        table.Columns.Add(new DataColumn("Col2", typeof(int)));
        table.Columns.Add(new DataColumn("Col3", typeof(double)));

        dr = table.NewRow();

        dr["Col1"] = DBNull.Value;
        dr["Col2"] = DBNull.Value;
        dr["Col3"] = DBNull.Value;

        table.Rows.Add(dr);

        ViewState["currentInflationTable"] = table;
        InflationGridView.DataSource = table;
        InflationGridView.DataBind();
    }



    // Button to add rows to the GridView
    protected void AddNewInflationRowButton_Click(object sender, EventArgs e)
    {
        AddNewInflationRow();
    }

    private void AddNewInflationRow()
    {
        int rowIndex = 0;

        if (ViewState["currentInflationTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["currentInflationTable"];
            DataRow drCurrentRow = null;
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    TextBox TextBoxStart =
                      (TextBox)InflationGridView.Rows[rowIndex].Cells[0].FindControl("StartInflationTextBox");
                    TextBox TextBoxEnd =
                      (TextBox)InflationGridView.Rows[rowIndex].Cells[1].FindControl("EndInflationTextBox");
                    TextBox TextBoxInflation =
                      (TextBox)InflationGridView.Rows[rowIndex].Cells[2].FindControl("InflationTextBox");

                    drCurrentRow = dtCurrentTable.NewRow();

                    int Num;
                    bool isNumStart = String.IsNullOrEmpty(TextBoxStart.Text.ToString()) ? true : int.TryParse(TextBoxStart.Text.ToString(), out Num);
                    bool isNumEnd = String.IsNullOrEmpty(TextBoxEnd.Text.ToString()) ? true : int.TryParse(TextBoxEnd.Text.ToString(), out Num);
                    bool isNumInflation = String.IsNullOrEmpty(TextBoxInflation.Text.ToString()) ? true : int.TryParse(TextBoxInflation.Text.ToString(), out Num);

                    if (!isNumStart || !isNumEnd || !isNumInflation)
                    {
                        this.ErrorInflationLabel.Text = "Incorrect input(s). All fields must be numeric.";
                        ErrorInflationLabel.ForeColor = System.Drawing.Color.Red;
                        this.ErrorInflationLabel.Visible = true;
                        this.InflationErrorUpdatePanel.Update();
                        return;

                    }
                    else if ((TextBoxStart.Text == "") || (TextBoxEnd.Text == "") || (TextBoxInflation.Text == ""))
                    {
                        this.ErrorInflationLabel.Text = "All fields must be completed.";
                        ErrorInflationLabel.ForeColor = System.Drawing.Color.Red;
                        this.ErrorInflationLabel.Visible = true;
                        this.InflationErrorUpdatePanel.Update();
                        return;

                    }
                    else if (TextBoxEnd.Text == HorizonTextBox.Text)
                    {
                        this.ErrorInflationLabel.Text = "Cannot set inputs beyond investment horizon.";
                        ErrorInflationLabel.ForeColor = System.Drawing.Color.Red;
                        this.ErrorInflationLabel.Visible = true;
                        this.InflationErrorUpdatePanel.Update();
                        return;
                    }
                    else
                    {
                        this.ErrorInflationLabel.Text = "";
                        this.InflationErrorUpdatePanel.Update();
                        dtCurrentTable.Rows[i - 1]["Col1"] = TextBoxStart.Text;
                        dtCurrentTable.Rows[i - 1]["Col2"] = TextBoxEnd.Text;
                        dtCurrentTable.Rows[i - 1]["Col3"] = TextBoxInflation.Text;                           
                        rowIndex++;
                    }
                }


                dtCurrentTable.Rows.Add(drCurrentRow);
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["Col1"] = (Convert.ToDouble(dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 2]["Col2"]) + 1).ToString();
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["Col2"] = HorizonTextBox.Text;

                ViewState["currentInflationTable"] = dtCurrentTable;

                InflationGridView.DataSource = dtCurrentTable;
                InflationGridView.DataBind();
            }
        }
        else
        {
            Response.Write("ViewState is null");
        }
        SetPreviousInflationData();
    }

    // Set data in previous rows when new row is added
    private void SetPreviousInflationData()
    {
        int rowIndex = 0;
        if (ViewState["currentInflationTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["currentInflationTable"];
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TextBox TextBoxStart = (TextBox)InflationGridView.Rows[rowIndex].Cells[0].FindControl("StartInflationTextBox");
                    TextBox TextBoxEnd = (TextBox)InflationGridView.Rows[rowIndex].Cells[1].FindControl("EndInflationTextBox");
                    TextBox TextBoxInflation =
                      (TextBox)InflationGridView.Rows[rowIndex].Cells[2].FindControl("InflationTextBox");

                    TextBoxStart.Text = dt.Rows[i]["Col1"].ToString();
                    TextBoxEnd.Text = dt.Rows[i]["Col2"].ToString();
                    TextBoxInflation.Text = dt.Rows[i]["Col3"].ToString();
                    rowIndex++;
                }
            }
        }
    }


 //************************* EXPORT TO CSV BY CLICKING ON SIMULATION BUTTON

    protected void retrieveInflationData()
    {
        if (Session["currentInflationTable"] != null)
        {
            DataTable dt = (DataTable)Session["currentInflationTable"]; ;

            if ((dt != null) && (dt.Rows.Count > 0))
            {
                InflationGridView.Visible = true;
                InflationGridView.DataSource = dt;
                InflationGridView.DataBind();
            }
            else
            {
                InflationGridView.Visible = false;
            }
        }
    }

    protected void RunSimulationButton_OnClick(object sender, EventArgs e)
    {
        retrieveInflationData();
        StreamWriter sw = new StreamWriter("C:\inst_research\MonteCarlo\gridview.csv");
        // now add the gridview header in csv file suffix with "," delimeter except last one
        for (int i = 0; i < InflationGridView.Columns.Count; i++)
        {
            sw.Write(InflationGridView.Columns[i].HeaderText);
            if (i != InflationGridView.Columns.Count)
            {
                sw.Write(",");
            }
        }
        // add new line
        sw.Write(sw.NewLine);
        // iterate through all the rows within the gridview
        foreach (GridViewRow dr in InflationGridView.Rows)
        {
            // iterate through all colums of specific row
            for (int i = 0; i < InflationGridView.Columns.Count; i++)
            {
                // write particular cell to csv file
                string test = dr.Cells[i].Text;
                sw.Write(dr.Cells[i].Text);
                if (i != InflationGridView.Columns.Count)
                {
                    sw.Write(",");
                }
            }
            // write new line
            sw.Write(sw.NewLine);
        }
        // flush from the buffers.
        sw.Flush();
        // closes the file
        sw.Close();
    }

2 个答案:

答案 0 :(得分:0)

自己解决了这个问题。由于GridView包含TemplateFields而不是BoundFields,因此应该做的是:

       StreamWriter sw = new StreamWriter("C:\inst_research\MonteCarlo\gridview.csv");
       foreach (GridViewRow row in InflationGridView.Rows)
        {

            foreach (TableCell cell in row.Cells)
            {
                string text = "";
                if (cell.Controls.Count > 0)
                {
                    foreach (Control control in cell.Controls)
                    {
                        switch (control.GetType().Name)
                        {
                            case "TextBox":
                                text = (control as TextBox).Text;
                                break;
                            case "DropDownList":
                                text = (control as DropDownList).SelectedItem.Text;
                                break;
                        }
                    }
                }
                else
                {
                    text = cell.Text;
                }
                sw.Write(text + ',');
            }
            sw.Write("\r\n");

        }

答案 1 :(得分:0)

    Response.Clear();

    Response.Buffer = true;

    Response.AddHeader("content-disposition",

     "attachment;filename=GridViewExport.csv");

    Response.Charset = "";

    Response.ContentType = "application/text";
    DataTable dt = new DataTable();
    string cn =      System.Configuration.ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString;
    SqlConnection con = new SqlConnection(cn);
    SqlCommand cmd = new SqlCommand("select a.Emp_Id,a.Emp_F_name,a.Emp_L_name,b.Dept_Name,a.Emp_dob,a.IsDeleted from Employee_tbl a Inner join Department_tbl b on a.Dept_Id=b.Dept_Id where a.IsDeleted='true'", con);
    con.Open();
    SqlDataAdapter adp = new SqlDataAdapter();
    DataSet dset = new DataSet();
    adp.SelectCommand = cmd;
    adp.Fill(dset);
    Gridview1.DataSource = dset.Tables[0];
    Gridview1.DataBind();
    Gridview1.AllowPaging = false;
    StringBuilder sb = new StringBuilder();


    int m;
    for (m = 0; m < Gridview1.Columns.Count; m++)
    {

        //add separator

        sb.Append(Gridview1.Columns[m].HeaderText+',' );

    }
    sb.Append("\r\n");
        for (int i = 0; i < Gridview1.Rows.Count; i++)
        {
            Label tt = Gridview1.Rows[i].FindControl("lblname") as Label;
            sb.Append(tt.Text + ',');
            tt = Gridview1.Rows[i].FindControl("Label4") as Label;
            sb.Append(tt.Text + ',');
            tt = Gridview1.Rows[i].FindControl("Label5") as Label;
            sb.Append(tt.Text );
            sb.Append("\r\n");
        }

    Response.Output.Write(sb.ToString());

    Response.Flush();

    Response.End();