通过C#创建具有特定列的CSV

时间:2018-03-21 08:46:45

标签: c# sql-server csv

我想基于SQL Server的基本查询创建一个csv文件,但是我应该在第一行和第二行创建列名称列描述,我该怎么办?我的问题是创建第二行,因为它不是由查询定义的,我不知道如何继续说出在前两行写什么。

你有一些例子吗?

现在我写了这个:

protected void ExportCSV(object sender, EventArgs e)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

    using (SqlConnection con = new SqlConnection(constr))

    {    
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))

        {    
            using (SqlDataAdapter sda = new SqlDataAdapter())

            {    
                cmd.Connection = con;

                sda.SelectCommand = cmd;

                using (DataTable dt = new DataTable())

                {    
                    sda.Fill(dt);

                    //Build the CSV file data as a Comma separated string.

                    string csv = string.Empty;     

                    foreach (DataColumn column in dt.Columns)

                    {    
                        //Add the Header row for CSV file.

                        csv += column.ColumnName + ',';

                    }   

                    //Add new line.

                    csv += "\r\n";     

                    foreach (DataRow row in dt.Rows)

                    {    
                        foreach (DataColumn column in dt.Columns)

                        {    
                            //Add the Data rows.

                            csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';    
                        }     

                        //Add new line.

                        csv += "\r\n";

                    }     

                    //Download the CSV file.

                    Response.Clear();

                    Response.Buffer = true;

                    Response.AddHeader("content-disposition", "attachment;filename=SqlExport.csv");

                    Response.Charset = "";

                    Response.ContentType = "application/text";

                    Response.Output.Write(csv);

                    Response.Flush();

                    Response.End();

                }

            }

        }

    }

}

此屏幕截图显示了我想要的第二行:

enter image description here

1 个答案:

答案 0 :(得分:0)

听起来我想在这里使用UNION声明;例如:

SELECT Hdr1, Hdr2, Hdr3
FROM DUAL
UNION
SELECT 'description1', 'description 2', 'description 3'
FROM DUAL
UNION
SELECT COLUMN1, COLUMN2, COLUMN3
FROM MYTABLE

编辑:

从C#开始,您可以执行以下操作:

foreach (DataColumn column in dt.Columns)
{    
    //Add the Header row for CSV file.
    csv += column.ColumnName + ',';
}   

//Add new line.
csv += Environment.NewLine;     
foreach (DataColumn column in dt.Columns)
{
    csv += $"{column.ExtendedProperties["Description"]},";
}

//Add new line.
csv += Environment.NewLine;     

显然,这取决于您配置扩展属性 - 如果还没有,那么您需要一个地方来获取列描述