您的位置:首页 > 编程语言 > ASP

ASP.NET DataGridView 导出CSV文件 后台代码

2017-02-23 09:35 295 查看
/// <summary>
/// Export the data from datatable to CSV file
/// </summary>
/// <param name="dt"></param>
public void ExportDataGridToCSV(DataTable dt)
{
string strFile = "";
string path = "";

//File info initialization
strFile = "Times_";
strFile = strFile + DateTime.Now.ToString("yyyyMMddhhmmss");
strFile = strFile + ".csv";
path = Server.MapPath(strFile);

System.IO.FileStream fs = new FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, new System.Text.UnicodeEncoding());

//Tabel header
for (int i = 0; i < dt.Columns.Count; i++)
{
sw.Write(dt.Columns[i].ColumnName);
sw.Write("\t");
}
sw.WriteLine("");

//Table body
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
sw.Write(dt.Rows[i][j].ToString());
sw.Write("\t");
}
sw.WriteLine("");
}

sw.Flush();
sw.Close();

DownLoadFile(path);
}

/// <summary>
/// DownLoadFile
/// </summary>
/// <param name="strFileName"></param>
private bool DownLoadFile(string strFileName)
{
try
{
System.IO.FileStream fs = System.IO.File.OpenRead(strFileName);
byte[] FileData = new byte[fs.Length];
fs.Read(FileData, 0, (int)fs.Length);
Response.Clear();
Response.AddHeader("Content-Type", "application/notepad");
string FileName = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(strFileName));
Response.AddHeader("Content-Disposition", "inline;filename=" + System.Convert.ToChar(34) + FileName + System.Convert.ToChar(34));
Response.AddHeader("Content-Length", fs.Length.ToString());
Response.BinaryWrite(FileData);
fs.Close();
System.IO.File.Delete(strFileName);
Response.Flush();
Response.End();
return true;
}
catch (Exception ex)
{
ex.Message.ToString();
return false;
}
}


保存DataTable缓存的机制:

1:使用Session

private void GetDataTable()
{
DataTable dt= GetDataTable();
Session["dt"]=dt;

GV_SpecView.DataSource = dt;
GV_SpecView.DataBind();
}




protected void btnDownLoad_Click(object sender, EventArgs e)
{
DataTable dt = Session["dt"] as DataTable;
if (dt.Rows.Count == 0)
{
Response.Write("<script>alert('No Record')</script>");
}
else
{
ExportDataGridToCSV(dt);
Session["SpecTable"] = null;
}
}

2:使用Cache

private void GetDataTable()
{
DataTable dt= GetDataTablee();
Cache.Insert("dt", dt, null, DateTime.Now.AddMinutes(2), System.Web.Caching.Cache.NoSlidingExpiration);
GV_SpecView.DataSource = dt;
GV_SpecView.DataBind();
}


protected void btnDownLoad_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)Cache["dt"];
if (dt.Rows.Count == 0)
{
Response.Write("<script>alert('No Record')</script>");
}
else
{
ExportDataGridToCSV(dt);
}
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ASP.NET CSV