从 SqlDataSource/GridView 生成 CSV 文件

发布于 2024-10-05 09:05:38 字数 105 浏览 6 评论 0原文

我需要能够在用户单击按钮时生成从 SqlDataSource/GridView 返回的结果的基本 CSV 文件,然后允许他们保存此文件。

这件事做起来简单吗?

谢谢

I need to be able to generate a basic CSV file of the results returned from an SqlDataSource/GridView upon the user clicking a button, then allow them to save this file.

Is this simple to do?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

柠栀 2024-10-12 09:05:38

由于您使用的是 SqlDataSource,那么您可以像这样从中获取 DataTable:

var dv = new DataView();
var dt = new DataTable();
dv = (DataView)mySQLDataSource.Select(DataSourceSelectArguments.Empty);
dt = dv.ToTable();

我写了一组 将 DataTable 转换为 CSV 的扩展方法,您应该能够轻松使用。

那么其余的代码将非常简单:

var csv = dt.ToCSV();

这是使用这种方法的完整示例。

标记:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="SO.WebUI._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeId"
        DataSourceID="SqlDataSourceLocal">
        <Columns>
            <asp:BoundField DataField="EmployeeId" HeaderText="EmployeeId" InsertVisible="False"
                ReadOnly="True" SortExpression="EmployeeId" Visible="False" />
            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
            <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
            <asp:BoundField DataField="Birthdate" HeaderText="Birthdate" SortExpression="Birthdate" />
        </Columns>
    </asp:GridView>

    <!-- This is the button to export CSV! -->
    <asp:Button ID="btnToCSV" runat="server" Text="Export to CSV" OnClick="GetCSV" />

    <asp:SqlDataSource ID="SqlDataSourceLocal" runat="server" 
    ConnectionString="<%$ ConnectionStrings:StackOverflowExamplesConnectionString %>"
        SelectCommand="SELECT * FROM [Employee]"></asp:SqlDataSource>
</asp:Content>

和隐藏代码:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public void GetCSV(object sender, EventArgs e)
    {
        DataView dv = (DataView)SqlDataSourceLocal.Select(DataSourceSelectArguments.Empty);
        var dt = dv.ToTable();

        var csv = dt.ToCSV();

        WriteToOutput(csv, "export.csv", "text/csv");
    }

    private void WriteToOutput(String csv, String fileName, String mimeType)
    {
        Response.Clear();
        Response.ContentType = mimeType;
        Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", fileName));
        Response.Write(csv);
        Response.End();
    }
}

就是这样。这里唯一没有包含的是扩展方法源,但由于我已经链接到它,因此将其放入静态类中应该没有问题。

Since you are using a SqlDataSource then you can get a DataTable out of it like this:

var dv = new DataView();
var dt = new DataTable();
dv = (DataView)mySQLDataSource.Select(DataSourceSelectArguments.Empty);
dt = dv.ToTable();

I wrote a set of extension methods to do DataTable to CSV, which you should be able to use easily.

The rest of your code would be pretty simple then:

var csv = dt.ToCSV();

Here is a full example using this very method.

The Markup:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="SO.WebUI._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeId"
        DataSourceID="SqlDataSourceLocal">
        <Columns>
            <asp:BoundField DataField="EmployeeId" HeaderText="EmployeeId" InsertVisible="False"
                ReadOnly="True" SortExpression="EmployeeId" Visible="False" />
            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
            <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
            <asp:BoundField DataField="Birthdate" HeaderText="Birthdate" SortExpression="Birthdate" />
        </Columns>
    </asp:GridView>

    <!-- This is the button to export CSV! -->
    <asp:Button ID="btnToCSV" runat="server" Text="Export to CSV" OnClick="GetCSV" />

    <asp:SqlDataSource ID="SqlDataSourceLocal" runat="server" 
    ConnectionString="<%$ ConnectionStrings:StackOverflowExamplesConnectionString %>"
        SelectCommand="SELECT * FROM [Employee]"></asp:SqlDataSource>
</asp:Content>

And the code-behind:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public void GetCSV(object sender, EventArgs e)
    {
        DataView dv = (DataView)SqlDataSourceLocal.Select(DataSourceSelectArguments.Empty);
        var dt = dv.ToTable();

        var csv = dt.ToCSV();

        WriteToOutput(csv, "export.csv", "text/csv");
    }

    private void WriteToOutput(String csv, String fileName, String mimeType)
    {
        Response.Clear();
        Response.ContentType = mimeType;
        Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", fileName));
        Response.Write(csv);
        Response.End();
    }
}

There you go. The only thing not included here is the extension method source, but since I've linked to it, you should have no problems getting that into a static class.

╰◇生如夏花灿烂 2024-10-12 09:05:38

对于 GridView 你可以使用这个:

            StreamWriter writer = new StreamWriter("file.csv");

            // Write columns
            writer.Write(myGridView.Columns[0].HeaderText);
            for (int i = 1; i < myGridView.Columns.Count; i++)
                writer.Write("," + myGridView.Columns[i].HeaderText);

            writer.Write("\n");

            // Write values
            for (int x = 0; x < myGridView.Rows.Count; x++)
            {
                writer.Write(myGridView.Rows[x].Cells[0].Text);
                for (int i = 1; i < myGridView.Rows[x].Cells.Count; i++)
                    writer.Write("," + myGridView.Rows[x].Cells[i].Text);

                writer.Write("\n");
            }

            writer.Close();

For a GridView you could use this:

            StreamWriter writer = new StreamWriter("file.csv");

            // Write columns
            writer.Write(myGridView.Columns[0].HeaderText);
            for (int i = 1; i < myGridView.Columns.Count; i++)
                writer.Write("," + myGridView.Columns[i].HeaderText);

            writer.Write("\n");

            // Write values
            for (int x = 0; x < myGridView.Rows.Count; x++)
            {
                writer.Write(myGridView.Rows[x].Cells[0].Text);
                for (int i = 1; i < myGridView.Rows[x].Cells.Count; i++)
                    writer.Write("," + myGridView.Rows[x].Cells[i].Text);

                writer.Write("\n");
            }

            writer.Close();
心奴独伤 2024-10-12 09:05:38

private void button13_Click(object sender, EventArgs e) // 导出到.csv
{
//OnExportGridToCSV();

       StreamWriter writer = new StreamWriter("C:\\scripts\\file.csv");

       // Write columns
       writer.Write(dataGridView1.Columns[0].HeaderText);
       for (int i = 1; i < dataGridView1.Columns.Count; i++)
           writer.Write("," + dataGridView1.Columns[i].HeaderText);

       writer.Write("\n");

       // Write values
       for (int x = 0; x < dataGridView1.Rows.Count; x++)
       {
           writer.Write(dataGridView1.Rows[x].Cells[0].FormattedValue.ToString());
           for (int i = 1; i < dataGridView1.Rows[x].Cells.Count; i++)
               writer.Write("," + dataGridView1.Rows[x].Cells[i].FormattedValue.ToString());

           writer.Write("\n");

           textBox5.Text = ("Row " + (x + 1).ToString() + " of " + dataGridView1.Rows.Count + " exported."); // progress indicator
       }


       writer.Close();



       // open up the newly created file in excel 

       Process proc = new Process();
       proc.StartInfo = new ProcessStartInfo("excel.exe", "C:\\scripts\\file.csv");
       proc.Start();
   }

private void button13_Click(object sender, EventArgs e) // export to .csv
{
//OnExportGridToCSV();

       StreamWriter writer = new StreamWriter("C:\\scripts\\file.csv");

       // Write columns
       writer.Write(dataGridView1.Columns[0].HeaderText);
       for (int i = 1; i < dataGridView1.Columns.Count; i++)
           writer.Write("," + dataGridView1.Columns[i].HeaderText);

       writer.Write("\n");

       // Write values
       for (int x = 0; x < dataGridView1.Rows.Count; x++)
       {
           writer.Write(dataGridView1.Rows[x].Cells[0].FormattedValue.ToString());
           for (int i = 1; i < dataGridView1.Rows[x].Cells.Count; i++)
               writer.Write("," + dataGridView1.Rows[x].Cells[i].FormattedValue.ToString());

           writer.Write("\n");

           textBox5.Text = ("Row " + (x + 1).ToString() + " of " + dataGridView1.Rows.Count + " exported."); // progress indicator
       }


       writer.Close();



       // open up the newly created file in excel 

       Process proc = new Process();
       proc.StartInfo = new ProcessStartInfo("excel.exe", "C:\\scripts\\file.csv");
       proc.Start();
   }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文