可能重复:
Efficient Method for Creating CSV String from Lists/SortedLists C#?
这里我需要使用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();
}
请告诉我更好的做法 感谢
答案 0 :(得分: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文件。