存储过程返回一个临时表,我需要将其转换为CSV文件

时间:2014-01-16 21:37:18

标签: sql-server csv datagridview datatable

我基本上有一个存储过程,我通过一个方法调用:

Time_Tracker.BLL.ResultsManager.GetCSV(Convert.ToDateTime("2014-01-11"));

它返回8列数据,范围从25到150条记录。

我需要能够将其转换为CSV文件到用户选择的路径。我能够将它作为一个数组(Results[] TEST = new Results[25];)放入我的代码中,并验证数据是O.K.我看到很多帖子都使用DataTable作为转换为CSV的来源,但我不确定如何从调用存储过程的方法加载DataTable。与DataGridView相同,不确定如何将数据加载到DataGridView

我也看到过他们使用SqlDataAdapter来填充DataTable的方法。由于我使用直接使用存储过程的方法,我不想每次都使用SqlDataAdapter并提供数据库配置信息。

如果有人可以帮助我将其加载到DataTableDataGridView,我想我可以从那里弄明白。

提前谢谢。

埃里克

4 个答案:

答案 0 :(得分:0)

只需定义数据表并使用load命令将数据从阅读器移动到数据表。

http://msdn.microsoft.com/en-us/library/d7125bke.aspx

这是从MSDN。我添加了两行来加载数据表。

-- Code from msdn
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();


cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;

sqlConnection1.Open();

SqlDataReader reader = cmd.ExecuteReader();

-- This is my addition
DataTable dt = new DataTable();
dt.Load(reader);

sqlConnection1.Close();

我仍然不明白你要做什么。您可以通过编码创建数据表,xml记录集。

以下代码可用于将数组转换为DataTable。您需要做一些工作来添加您的详细信息。

http://msdn.microsoft.com/en-us/library/skef0k7a(v=vs.110).aspx

// Create sample Customers table.
DataTable table = new DataTable();
table.TableName = "Customers";

// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));

// Set the ID column as the primary key column.
table.PrimaryKey = new DataColumn[] { idColumn };

table.Rows.Add(new object[] { 0, "Mary" });
table.Rows.Add(new object[] { 1, "Andy" });
table.Rows.Add(new object[] { 2, "Peter" });
table.AcceptChanges();
return table;

我希望这会有所帮助。如果没有,我仍然没有达到业务要求。

答案 1 :(得分:0)

我现在可以从Datatable(谢谢你)创建一个CSV文件。 我现在的问题是其中一列是SQL中的DATE,但是C#中的DateTime, 所以它包括时间(2014年1月17日12:00:00)和日期。 如果您查看下面的代码,我能够检测到时间组件仍然附加的日期。但是,我似乎无法将其解析为写入CSV文件的日期。任何帮助将不胜感激!

这是我最终做的事情:

protected void btnCSV_Click(object sender,EventArgs e)

{

SqlConnection sqlConnection1 = new SqlConnection(DAL.DBUtils.SqlConnectionString);

        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = "[dbo].[usp.CSV_OUT]";

        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@DateBeg", "2014-01-11");

        cmd.Connection = sqlConnection1;

        sqlConnection1.Open();

        SqlDataReader reader = cmd.ExecuteReader();

        DataTable dt = new DataTable();

        dt.Load(reader);

        sqlConnection1.Close();

        ExportToCSV(dt, @"C:\Users\eric.dahlenburg\Documents\Visual Studio 2010\Projects\", "csvData.csv");
    }

    public static void ExportToCSV(DataTable dt, string strFilePath, string fileName)
    {
        var sw = new StreamWriter(strFilePath + fileName, false);
        // Write the headers.
        int iColCount = dt.Columns.Count;
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dt.Columns[i]);
            if (i < iColCount - 1) sw.Write(",");
        }
        sw.Write(sw.NewLine);
        // Write rows.
        foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (dr[i] is DateTime)
                {
                    if (((DateTime)dr[i]).TimeOfDay.TotalSeconds == 0) // Time Since Midnight (in Seconds)
                    {
                        dr[i] = ((DateTime)dr[i]).ToString("yyyy-MM-dd");
                    }
                    else
                    {
                        dr[i] = ((DateTime)dr[i]).ToString("yyyy-MM-dd HH:mm:ss");
                    }
                }

                if (!Convert.IsDBNull(dr[i]))
                {
                    if (dr[i].ToString().StartsWith("0"))
                    {
                        sw.Write(@"=""" + dr[i] + @"""");
                    }
                    else
                    {
                        sw.Write(dr[i].ToString());
                    }
                }

                if (i < iColCount - 1) sw.Write(",");
            }
            sw.Write(sw.NewLine);
        }
        sw.Close();
    } 

答案 2 :(得分:0)

我想通了(见下文)。我将此标记为已解决,再次感谢您的帮助!

       foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
              if (!Convert.IsDBNull(dr[i]))
                {
                    if (dr[i] is DateTime)
                    {
                        if (((DateTime)dr[i]).TimeOfDay.TotalSeconds == 0) // Time Since Midnight (in Seconds)
                        {
                            sw.Write(((DateTime)dr[i]).ToString("yyyy-MM-dd"));
                        }
                    }

                    else
                    {
                        sw.Write(dr[i].ToString());
                    }
                }

                if (i < iColCount - 1) sw.Write(",");
            }
            sw.Write(sw.NewLine);
        }

答案 3 :(得分:0)

以下是我为其他寻求帮助的人所做的事情:

  protected void btnCSV_Click(object sender, EventArgs e)
    {
        try
        {
            // HATE EXPOSING THE DATABASE CONNECTION THIS WAY !!!
            SqlConnection sqlConnection1 = new SqlConnection(DAL.DBUtils.SqlConnectionString);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "[dbo].[usp.CSV_OUT]";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@DateBeg", Time_Tracker.Utilities.TimeCard_Start_Date());
            cmd.Connection = sqlConnection1;
            sqlConnection1.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(reader);
            sqlConnection1.Close();
            ExportToCSV(dt, ConfigurationManager.AppSettings["CSVPath"].ToString(), "CSV_Hours_Data_" + Time_Tracker.Utilities.TimeCard_Start_Date().AddDays(+6).ToString("MM_dd_yyyy") + ".csv");
        }
        catch (Exception ex)
        {
            Utilities.ErrorLog(ex.Message, ex.GetType().ToString(), ex.StackTrace, @"Time_Tracker.txt");
        }
    }


    public static void ExportToCSV(DataTable dt, string strFilePath, string fileName)
    {
        try
        {
            var sw = new StreamWriter(strFilePath + fileName, false);
            // Write the headers.
            int iColCount = dt.Columns.Count;
            for (int i = 0; i < iColCount; i++)
            {
                sw.Write(dt.Columns[i]);
                if (i < iColCount - 1) sw.Write(",");
            }
            sw.Write(sw.NewLine);
            // Write rows.
            foreach (DataRow dr in dt.Rows)
            {
                for (int i = 0; i < iColCount; i++)
                {
                    if (!Convert.IsDBNull(dr[i]))
                    {
                        string output = dr[i].ToString();

                        if (dr[i] is DateTime)
                        {
                            if (((DateTime)dr[i]).TimeOfDay.TotalSeconds == 0) // Time Since Midnight (in Seconds)
                            {
                                output = (((DateTime)dr[i]).ToString("yyyy-MM-dd"));
                            }
                        }
                        if (output.Contains(";") || output.Contains("\""))
                            output = '"' + output.Replace("\"", "\"\"") + '"';
                        if (Regex.IsMatch(output, @"(?:\r\n|\n|\r)"))
                            output = string.Join(" ", Regex.Split(output, @"(?:\r\n|\n|\r)"));
                        sw.Write(output);
                    }

                    if (i < iColCount - 1) sw.Write(",");
                }
                sw.Write(sw.NewLine);
            }
            sw.Close();
            // Causes Save As Dialog box to appear for user.
            String FileName = fileName;
            String FilePath = strFilePath;
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/plain";
            response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
            response.TransmitFile(FilePath + FileName);
            response.Flush();
            response.End();

        }
        catch (Exception ex)
        {
            Utilities.ErrorLog(ex.Message, ex.GetType().ToString(), ex.StackTrace, @"Time_Tracker.txt");
        }
    }