做OA的时候,客户需要把结果输出成CSV文件!CSV文件是可以用Excel打开,其可以换行的字号是回车,在C#中是 \n
下面是代码把一个Table转换成字符串,一个CSV可以解析的字符串!
CSVConvert.aspx后台代码
protected void Page_Load(object sender, EventArgs e) { DataTable dt = (DataTable)Session["Source"]; ConvertCSV(dt, "a"); //Response.Redirect(); } /// <summary> /// 导出cvs文件 /// </summary> /// <param name="dt"></param> /// <param name="reportFileName"></param> private void ConvertCSV(DataTable dt, string reportFileName) { StringBuilder sBuilder = new StringBuilder(""); //string strCSV = string.Empty; for (int i = 0; i < dt.Columns.Count; i++) { if (i == 0) { sBuilder = sBuilder.Append("\"").Append(dt.Columns[i].ColumnName).Append("\""); //strCSV += "\"" + dt.Columns[i].ColumnName + "\""; } else { sBuilder = sBuilder.Append(",\"").Append(dt.Columns[i].ColumnName).Append("\""); //strCSV += ",\"" + dt.Columns[i].ColumnName + "\""; } } sBuilder = sBuilder.Append("\r\n"); //strCSV += "\r\n"; for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { if (j == 0) { sBuilder = sBuilder.Append("\"").Append(ConvertObject(dt.Rows[i][j])).Append("\""); //strCSV += "\"" + ConvertObject(dt.Rows[i][j]) + "\""; } else { sBuilder = sBuilder.Append(",\"").Append(ConvertObject(dt.Rows[i][j])).Append("\""); //strCSV += ",\"" + ConvertObject(dt.Rows[i][j]) + "\""; } } sBuilder = sBuilder.Append("\r\n"); //strCSV += "\r\n"; } byte[] bFile = System.Text.Encoding.GetEncoding("GB2312").GetBytes(sBuilder.ToString()); Session["ReporFrom"] = bFile; Session["reporFileName"] = reportFileName; Response.Redirect("ReportForm.aspx"); //Response.Write("<script language='javascript'>window.open('ReportForm.aspx');</script>"); //Response.Write("<script language='javascript'>window.open('ReportForm.aspx');</script>"); } protected string ConvertObject(object obj) { if (obj != null) { return obj.ToString(); } return string.Empty; }
下面是ReportForm.aspx 页面代码
protected void Page_Load(object sender, EventArgs e) { byte[] bFile = (byte[]) Session["ReporFrom"]; string reportFileName = Session["reporFileName"].ToString(); Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); Response.AddHeader("Content-Disposition", "attachment; filename=" + reportFileName + ".csv"); Response.ContentType = "application/octet-stream;charset=GB2312"; Response.AddHeader("Content-length", bFile.Length.ToString()); Response.BinaryWrite(bFile); Response.End(); Response.Close(); Session.Remove("ReporFrom"); Session.Remove("reporFileName"); }
下面是具体的实例用法:
Session["Source"] = dt; Response.Write("<script language='javascript'>window.open('CSVConvert.aspx');</script>");