C#生成的CSV更改从SQL数据库检索的数据的格式

时间:2017-02-06 05:47:33

标签: c# sql sql-server excel

protected void ExportCSV(object sender, EventArgs e)
{

DataTable ds = new DataTable();
ds.Columns.AddRange(new DataColumn[1] { new DataColumn("Name") });
foreach (GridViewRow roww in GridView1.Rows)

{
    if (roww.RowType == DataControlRowType.DataRow)
    {
        CheckBox chkRow = (roww.Cells[0].FindControl("chkRow") as CheckBox);

        if (chkRow.Checked)
        {
            string name = roww.Cells[1].Text;
            string DefaultConnection = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            using (SqlConnection con = new SqlConnection(DefaultConnection))

            {
                SqlCommand command = new SqlCommand();

                using (SqlCommand cmd = new SqlCommand("Select AssignNumber, Stage.StageName,Stage.StationName,AspNetUsers.UserName,RecordedDateTime,StartTime,EndTime,Duration,PauseCount,PauseTotalTime,StageRecord.Count, StageRecord.Notes,Location,VarName,DropOut From TimingProfile Inner Join StudyRecord ON TimingProfile.TimingProfileID = StudyRecord.TimingProfileID Inner Join StageRecord ON StudyRecord.StudyRecordID = StageRecord.StudyRecordID Left Join Stage ON StageRecord.StageID = Stage.StageID Left Join VarAffect ON StageRecord.VarID = VarAffect.VarID Left Join MultiNameValue ON StudyRecord.StudyRecordID = MultiNameValue.StudyRecordID Left Join UserStage ON UserStage.StageID = Stage.StageID Left Join AspNetUsers ON UserStage.UserID = AspNetUsers.Id Where TimingProfile.Name = " + "'"+name+"'"))

                    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";
                            }
                            DateTime localdate = DateTime.Now;
                        //Download the CSV file.

                        Response.Clear();
                            Response.Buffer = true;
                            Response.AddHeader("content-disposition", "attachment;filename=MultiStation" + "" + name + " " + localdate + ".csv");

                        Response.Charset = "";
                            Response.ContentType = "application/text";
                            Response.Output.Write(csv);

                        Response.Flush();
                        Response.End();

                    }
                }

            }
            }

        }
    }
} 

当我在SQL管理工作室中使用查询时,持续时间显示为:00:32:39但它在生成的CSV中显示为0.0226736111111111。有没有办法纠正这个问题?

1 个答案:

答案 0 :(得分:0)

有人需要说出来。这段代码显示了loada的热情,并没有太多的复杂性。您已经在一种方法中混淆了UI(复选框),业务逻辑,数据访问,序列化和HTTP!并且,可以预见,存在问题。您的SQL是带有连接的字符串文字,最后隐藏的是一个发光的SQL注入漏洞。您的序列化代码(将逗号转换为分号)会丢失数据并生成无效的CSV(双引号不会加倍)。不使用stringbuilder构建CSV很可能会导致性能问题。使用库,Dapper或QueryFirst(免责声明:我写的)进行数据访问,使用服务堆进行序列化,可以避免所有这些陷阱。

了解数据的存储方式以及格式化的方式和时间,对于程序员来说,确实是一项核心竞争力。在最后一刻格式化通常是件好事。如果您正在重用sql请求,则可能需要在C#中进行格式化。由于此请求仅用于此位置,因此您可能希望直接在SQL中进行格式化。缺点是C#不会将持续时间视为持续时间。在构建自己的日期时间格式之前,请尝试使用内置的日期时间格式。