我的代码导出 .CVS 花费的时间太长,我们正在谈论几分钟。查询需要几秒钟才能在 SQL 中执行。
这就是我现在要填充 DT 的内容:
using (SqlConnection myConnection = new SqlConnection(connString))
{
using (SqlCommand myCommand = new SqlCommand(sqlString, myConnectionString))
{
myCommand.Parameters.AddWithValue("@DATE1", Date1);
myCommand.Parameters.AddWithValue("@DATE2", Date2);
myCommand.CommandTimeout = 0;
myConnection.Open();
using (SqlDataReader myReader = myCommand.ExecuteReader())
{
DataTable myTable = new DataTable();
myTable.Load(myReader);
return myTable;
}
}
}
这就是我用来创建 .CVS 文件的内容:
protected void ExportToCSV(object sender, EventArgs e)
{
DataTable dt = ContactProvider.GetDataTable(Date1, Date2);
DataRow row;
foreach (System.Data.DataColumn col in dt.Columns) col.ReadOnly = false;
//I use this to change the value of the columns, because EXCEL changes the string to a date -.-
for (int i = 0; i < dt.Rows.Count; i++)
{
row = dt.Rows[i];
if (dt.Rows[i][5].ToString() == "MAR2")
{
row[5] = "=\"MAR2\"";
}
if (dt.Rows[i][5].ToString() == "MAR1")
{
row[5] = "=\"MAR1\"";
}
}
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition","attachment;filename=Report.csv");
Response.Charset = "";
Response.ContentType = "application/text";
StringBuilder sb = new StringBuilder();
for (int k = 0; k < dt.Columns.Count; k++)
{
sb.Append(dt.Columns[k].ColumnName + ',');
}
sb.Append("\r\n");
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
sb.Append(dt.Rows[i][k].ToString().Replace(",", ";") + ',');
}
sb.Append("\r\n");
}
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
有没有办法可以提高这些方法的性能,以便我可以尽快填充 DT 并导出 .CVS?
感谢您的帮助,我真的需要改进这个东西!