1.导出为cvs
首先要获取一连串的string类型的字符串,然后确定导出格式.... 先获取表格的头,这个header不管你是固定还是动态,每个字段后面加一个",",用来表示一列;到最后换行时加Environment.NewLine;例如: ArrayList list = new ArrayList(); list.Add("xxx"); list.Add("xx"); list.Add("xx"); list.Add("xx"); list.Add("xxx"); list.Add("xx"); list.Add("xx"); list.Add("xx"); list.Add("xxxx"); string[] saleHeaders = (string[])list.ToArray(typeof(string)); temp = saleWriteOffHtmlStr(saleDt, saleHeaders); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(temp.ToString()); byte[] outBuffer = new byte[buffer.Length + 3]; outBuffer[0] = (byte)0xEF; outBuffer[1] = (byte)0xBB; outBuffer[2] = (byte)0xBF; Array.Copy(buffer, 0, outBuffer, 3, buffer.Length); Response.Write(Encoding.UTF8.GetString(outBuffer)); Response.Buffer = true; Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode("销售数据") + ".csv;"); Response.Charset = "utf-8"; Response.ContentType = "text/csv"; public string saleWriteOffHtmlStr(DataTable dt, string[] headers) { string htmlstr = "";
foreach (string s in headers) { htmlstr += s.ToString().Replace(',', ',') + ","; } htmlstr = htmlstr.Substring(0,htmlstr.Length-1) + Environment.NewLine; foreach (DataRow dr in dt.Rows) { htmlstr += dr["Base_tabletNumber"].ToString().Replace(',', ',') + ","; ....... htmlstr += Environment.NewLine; } return htmlstr; }
2.导出为xls
HttpResponse resp; resp = Page.Response; resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); resp.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode("销售表", System.Text.Encoding.UTF8) + ".xls;"); resp.Write(temp); temp = ""; resp.End(); public string saleWriteOffHtmlStr(DataTable dt, string[] headers) { string htmlstr = ""; foreach (string s in headers) { htmlstr += s.ToString().Replace(',', ',') + "\t"; } htmlstr = htmlstr.Substring(0, htmlstr.Length - 1) + "\n"; foreach (DataRow dr in dt.Rows) { htmlstr += dr["Base_tabletNumber"].ToString().Replace(',', ',') + "\t"; ..................... ..................... htmlstr += "\n"; } return htmlstr; }
System.Web.HttpUtility.UrlEncode("销售表", System.Text.Encoding.UTF8) 处理文件名乱码问题