如何将GridView导出到光盘上的CSV文件?

时间:2018-11-23 13:23:57

标签: asp.net gridview export-to-csv xls

我有一个导出按钮,可以将gridview导出到磁盘上的excel文件。但是,我也想导出它-没有任何对话框-到磁盘上的csv文件。我该怎么办?

        var sw = new StringWriter();
        var htw = new HtmlTextWriter(sw);

        // Render grid view control.
        grd.RenderControl(htw);

        // Write the rendered content to a file.
        string renderedGridView = sw.ToString();
        File.WriteAllText(@"C:\Sheets\" + "_Orders.xls", renderedGridView);

1 个答案:

答案 0 :(得分:0)

private void ExportToCsc()
{
    grd.AllowPaging = false;
    grd.DataBind();

    var sb = new StringBuilder();

    for (var i = 0; i < grd.Columns.Count; i++)
    {
        //add separator
        sb.Append(StringToCSVCell(grd.Columns[i].HeaderText));

        if (i + 1 != grd.Columns.Count)
        {
            sb.Append(",");
        }
    }

    //append new line
    sb.Append("\r\n");

    for (var i = 0; i < grd.Rows.Count; i++)
    {
        for (var j = 0; j < grd.Columns.Count; j++)
        {
            //add separator
            sb.Append(StringToCSVCell(grd.Rows[i].Cells[j].Text));

            if (j + 1 != grd.Columns.Count)
            {
                sb.Append(",");
            }
        }

        //append new line
        sb.Append("\r\n");
    }

    // Below line of code save the file in folder path you specified.
    var folderPath = "C:\\Sheets\\";

    File.WriteAllText(folderPath + "_Orders.csv", sb.ToString());

    grd.AllowPaging = true;
    grd.DataBind();
}

public static string StringToCSVCell(string str)
{
    var mustQuote = (str.Contains(",") || str.Contains("\"") || str.Contains("\r") || str.Contains("\n"));
    if (mustQuote)
    {
        var  sb = new StringBuilder();
        sb.Append("\"");

        foreach (var nextChar in str)
        {
            sb.Append(nextChar);

            if (nextChar == '"')
            {
                sb.Append("\"");
            {
        }

        sb.Append("\"");
        return sb.ToString();
    }

    return str;
}