1

可能重复:
从 Lists/SortedLists C# 创建 CSV 字符串的有效方法?

这里我需要使用 c# 将数据库信息导出到 .csv 文件,

在这里,我给出了我的代码,但加载到 csv 文件需要更多时间

public void CSVFile(DataTable table, string FilePath)
{
// Create the CSV file to which grid data will be exported.
StreamWriter swr = new StreamWriter(FilePath, false);
//First we will write the headers.
int iColCount = table.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
    swr.Write(dtDataTablesList.Columns[i]);
    if (i < iColCount - 1)
    {
        swr.Write(",");
    }
}
swr.Write(swr.NewLine);

// Now write all the rows.
foreach (DataRow dr in table.Rows)
{
    for (int i = 0; i < iColCount; i++)
    {
        if (!Convert.IsDBNull(dr[i]))
        {
            swr.Write(dr[i].ToString());
        }
        if (i < iColCount - 1)
        {
            swr.Write(",");
        }
    }
    swr.Write(sw.NewLine);
}
swr.Close();
}

请告诉我更好的方法谢谢

4

1 回答 1

0

是的,最近我有同样的问题,

我有解决方案,试试这个代码。

private void button1_Click(object sender, EventArgs e)
{
    Stopwatch swra = new Stopwatch();
    swra.Start();
    string NewconnectionString = "myCoonectionString";
    StreamWriter CsvfileWriter = new StreamWriter(@"D:\testfile.csv");
    string sqlselectQuery = "select * from Mytable";
    SqlCommand sqlcmd = new SqlCommand();

    SqlConnection spContentConn = new SqlConnection(NewconnectionString);
    sqlcmd.Connection = spContentConn;
    sqlcmd.CommandTimeout = 0;
    sqlcmd.CommandType = CommandType.Text;
    sqlcmd.CommandText = sqlselectQuery;
    spContentConn.Open();
    using (spContentConn)
    {
        using (SqlDataReader sdr = sqlcmd.ExecuteReader())
        using (CsvfileWriter)
        {
            //For getting the Table Headers
            DataTable Tablecolumns = new DataTable();

            for (int i = 0; i < sdr.FieldCount; i++)
            {
                Tablecolumns.Columns.Add(sdr.GetName(i));
            }
            CsvfileWriter.WriteLine(string.Join(",", Tablecolumns.Columns.Cast<datacolumn>().Select(csvfile => csvfile.ColumnName)));
            //For table headers

            while (sdr.Read())
            //based on your columns
                YourWriter.WriteLine(sdr[0].ToString() + "," + sdr[1].ToString() + "," +   
sdr[2].ToString() + "," + sdr[3].ToString() + "," + sdr[4].ToString() + "," + 
sdr[5].ToString() + "," + sdr[6].ToString() + "," + sdr[7].ToString() + "," + 
sdr[8].ToString() + "," + sdr[9].ToString() + "," + sdr[10].ToString() + "," + 
sdr[11].ToString() + ",");

        }
    }
   swra.Stop();
Console.WriteLine(swra.ElapsedMilliseconds);
}

使用此代码,我们可以使用 datareader 快速将数据库信息导出到 csv 文件。

于 2012-09-24T11:10:34.580 回答