Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 存储过程返回需要转换为CSV文件的临时表_Sql Server_Csv_Datagridview_Datatable - Fatal编程技术网

Sql server 存储过程返回需要转换为CSV文件的临时表

Sql server 存储过程返回需要转换为CSV文件的临时表,sql-server,csv,datagridview,datatable,Sql Server,Csv,Datagridview,Datatable,我基本上有一个通过方法调用的存储过程: Time_Tracker.BLL.ResultsManager.GetCSV(Convert.ToDateTime("2014-01-11")); 它返回8列数据,范围从25到150条记录 我需要能够将其转换为CSV文件到用户选择的路径。我可以将它作为数组Results[]TEST=newresults[25]放入我的代码中;并且已经验证了数据是否正确。我看到很多帖子都使用DataTable作为转换为CSV的源,但我不确定如何从调用存储过程的方法加载Da

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

Time_Tracker.BLL.ResultsManager.GetCSV(Convert.ToDateTime("2014-01-11"));
它返回8列数据,范围从25到150条记录

我需要能够将其转换为CSV文件到用户选择的路径。我可以将它作为数组Results[]TEST=newresults[25]放入我的代码中;并且已经验证了数据是否正确。我看到很多帖子都使用DataTable作为转换为CSV的源,但我不确定如何从调用存储过程的方法加载DataTable。DataGridView也是一样,也不知道如何将数据加载到DataGridView中

我还看到了使用SqlDataAdapter填充数据表的方法。由于我使用直接处理存储过程的方法,所以我不想每次都使用SqlDataAdapter并提供数据库配置信息

如果有人能帮我把它加载到DataTable或DataGridView中,我想我可以从那里找到答案

先谢谢你


Eric

只需定义一个数据表,并使用load命令将数据从读卡器移动到数据表

-- 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();
这是来自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记录集

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


我希望这有帮助。如果没有,我仍然无法满足业务需求。

我已经解决了,请参见下文。我会将此标记为已解决,再次感谢您的帮助

       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);
        }

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

  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");
        }
    }

除了将数据从数据库传递到csv文件之外,您还需要处理程序中的数据吗?数据中可能有空值吗?数据中可能有逗号吗?我没有看到将帖子标记为已回复的链接。有人能把这根线收起来吗?谢谢