DataTable内容导出为CSV文件

CSVHelper.cs内容:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Web;
  6 using System.Threading;
  7 using System.IO;
  8 using System.Data;
  9 using System.Windows.Forms;
 10
 11 namespace IMSCommonFunction
 12 {
 13     public class CSVHelper
 14     {
 15         public static string FilterCSVCell(string cellContent)
 16         {
 17             bool isAddFlag = false;
 18             if (cellContent.IndexOf("\"") != -1)
 19             {
 20                 cellContent = cellContent.Replace("\"", "\"\"");
 21                 cellContent = "\"" + cellContent + "\"";
 22                 isAddFlag = true;
 23             }
 24             if (cellContent.IndexOf(",") != -1 && isAddFlag != true)
 25             {
 26                 cellContent = "\"" + cellContent + "\"";
 27             }
 28             return cellContent;
 29         }
 30
 31         public static void ExportCSVFile(HttpResponse response, string fullPath, string Content)
 32         {
 33             try
 34             {
 35                 response.Buffer = true;
 36                 response.Clear();
 37                 response.Charset = System.Text.Encoding.Default.BodyName;
 38                 response.ContentEncoding = System.Text.Encoding.UTF8;// System.Text.Encoding.GetEncoding("GB2312");//GB2312用Excel打开时,没有乱码。
 39                 response.AppendHeader("Content-Disposition", "attachment;filename=" + fullPath);
 40                 response.ContentType = "application/ms-excel";
 41                 response.Output.Write(Content);
 42                 response.Flush();
 43                 response.End();
 44             }
 45             catch (ThreadAbortException)
 46             {
 47             }
 48             catch (Exception ex)
 49             {
 50                 throw new ApplicationException(string.Format("Export CSV file have a error: {0}", fullPath), ex);
 51             }
 52         }
 53
 54         public static void FileDownload(string FullFileName)
 55         {
 56             FileInfo DownloadFile = new FileInfo(FullFileName);
 57             System.Web.HttpContext.Current.Response.Clear();
 58             System.Web.HttpContext.Current.Response.ClearHeaders();
 59             System.Web.HttpContext.Current.Response.Buffer = false;
 60             string extension = Path.GetExtension(FullFileName);
 61             extension = string.IsNullOrEmpty(extension) ? extension : extension.ToLower();
 62             switch (extension)
 63             {
 64                 case ".xml":
 65                     System.Web.HttpContext.Current.Response.ContentType = "text/xml";
 66                     break;
 67                 default:
 68                     System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
 69                     break;
 70             }
 71             string browser = System.Web.HttpContext.Current.Request.UserAgent.ToUpper();
 72             bool isNeedEncode = !browser.Contains("FIREFOX");
 73             System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" +
 74                 (isNeedEncode ? System.Web.HttpUtility.UrlEncode(DownloadFile.Name, System.Text.Encoding.UTF8) : DownloadFile.Name));
 75             System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
 76             System.Web.HttpContext.Current.Response.Flush();
 77             if (System.Web.HttpContext.Current.Response.IsClientConnected)
 78                 System.Web.HttpContext.Current.Response.WriteFile(DownloadFile.FullName);
 79
 80             //出错
 81             System.Web.HttpContext.Current.Response.End();
 82             System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
 83         }
 84
 85         public static void DataHtmlToExcel(HttpResponse response, DataTable dt, string strFileName)
 86         {
 87             string style = @"<style> .text { mso-number-format:\@; } </script> "; //设置格式
 88             //设置Response
 89             response.Clear();
 90             response.Buffer = true;
 91             response.Charset = "utf-8";
 92             response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
 93             //Response.Charset = "utf-8";
 94             if (strFileName.Length > 0)
 95             {
 96                 response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Encoding.UTF8.GetBytes(strFileName)));
 97             }
 98             else
 99             {
100                 response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls");
101             }
102             //Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
103             HttpContext.Current.Response.ContentType = "application/ms-excel";
104
105             //绑定数据到DataGrid1
106             System.Web.UI.WebControls.DataGrid DataGrid1 = new System.Web.UI.WebControls.DataGrid();
107             DataGrid1.DataSource = dt.DefaultView;
108             DataGrid1.DataBind();
109             //将DataGrid1构成的html代码写进StringWriter
110             //DataGrid1.Page.EnableViewState = false;
111             System.IO.StringWriter tw = new System.IO.StringWriter();
112             System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
113             DataGrid1.RenderControl(hw);
114
115             response.Write(style);//注意
116             response.Write(tw.ToString());
117             response.Flush();
118             response.End();
119         }
120
121         public static void ExportExcel(HttpResponse response, DataTable dt, string filename)
122         {
123             try
124             {
125                 response.Clear();
126                 response.BufferOutput = true;
127                 response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
128                 response.AppendHeader("Content-Disposition", "attachment;filename=" +
129                     HttpUtility.UrlEncode(Encoding.UTF8.GetBytes(filename)));
130                 response.ContentType = "application/ms-excel";
131                 StringBuilder colHeaders = new StringBuilder();
132                 StringBuilder items = new StringBuilder();
133
134                 DataRow[] dr = dt.Select();
135
136                 int i = 0;
137                 int clength = dt.Columns.Count;
138
139                 for (i = 0; i < clength; i++)
140                 {
141                     if (i == clength - 1)
142                     {
143                         colHeaders.Append(dt.Columns[i].Caption.ToString() + "\n");
144                     }
145                     else
146                     {
147                         colHeaders.Append(dt.Columns[i].Caption.ToString() + "\t");
148                     }
149                 }
150                 response.Write(colHeaders.ToString());
151
152                 foreach (DataRow row in dr)
153                 {
154                     for (i = 0; i < clength; i++)
155                     {
156                         if (i == clength - 1)
157                         {
158                             items.Append(row[i].ToString() + "\n");
159                         }
160                         else
161                         {
162                             items.Append(row[i].ToString() + "\t");
163                         }
164                     }
165                 }
166                 response.Write(items.ToString());
167             }
168             catch (Exception ex)
169             {
170                 response.Write(ex.Message);
171             }
172             finally
173             {
174                 response.Flush();
175                 response.End();
176             }
177         }
178
179         public static void DataTableToCSV(DataTable table, string file)
180         {
181             string title = "";
182             FileStream fs = new FileStream(file, FileMode.Create);
183             StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);
184             for (int i = 0; i < table.Columns.Count; i++)
185             {
186                 title += table.Columns[i].ColumnName + ",";
187             }
188             title = title.Substring(0, title.Length - 1) + "\n";
189             sw.Write(title);
190             foreach (DataRow row in table.Rows)
191             {
192                 string line = "";
193                 for (int i = 0; i < table.Columns.Count; i++)
194                 {
195                     line += row[i].ToString() + ",";
196                 }
197                 line = line.Substring(0, line.Length - 1) + "\n";
198                 sw.Write(line);
199             }
200             sw.Close();
201             fs.Close();
202         }
204     }
205 }

页面后台按钮事件处理:

 1 protected void btnExportCSV_Click(object sender, EventArgs e)
 2 {
 3     try
 4     {
 5         string sql = Server.UrlDecode(Request["Sql"]);
 6         DataTable dt = Bll.Report.CustomReport.GetCustomReport(sql);
 7         StringBuilder sbHeader = new StringBuilder();
 8         StringBuilder sbContent = new StringBuilder();
 9         DateTime tempDateTime = DateTime.MinValue;
10         string tempVal = "";
11         for (int i = 0, len = dt.Rows.Count; i < len; i++)
12         {
13             for (int j = 0, len2 = dt.Columns.Count; j < len2; j++)
14             {
15                 if (i == 0)
16                 {
17                     sbHeader.AppendFormat("{0},", dt.Columns[j].ColumnName);
18                 }
19                 tempVal = dt.Rows[i][j].ToString();
20                 if(DateTime.TryParse(tempVal,out tempDateTime))
21                     tempVal = tempDateTime.ToString("dd-MM-yyyy HH:mm:ss");
22                 sbContent.AppendFormat("{0},", IMSCommonFunction.CSVHelper.FilterCSVCell(tempVal));
23             }
24             sbContent.Remove(sbContent.Length - 1, 1);
25             sbContent.AppendLine();
26         }
27         sbHeader.Remove(sbHeader.Length - 1, 1);
28         sbHeader.AppendLine();
29         IMSCommonFunction.CSVHelper.ExportCSVFile(this.Response,
30                                                   string.Format("CustomReport_{0}.csv", DateTime.Now.ToString("ddMMyyyy_HHmmss")),
31                                                   sbHeader.ToString() + sbContent.ToString());
32     }
33     catch (Exception ex)
34     {
35         IMSCommonFunction.SystemEventLog.LogEvent("CustomReport.aspx,export csv file Errormsg", ex, "common", this.CurrentUserId);
36         this.ShowErrorMsg(ex);
37     }
38 }
时间: 2024-11-13 08:59:43

DataTable内容导出为CSV文件的相关文章

原创 Datareader 导出为csv文件方法

DataReader 是游标只读数据, 如果是大数据导出,用Datatable 将耗费巨大内存资源.因为Datatable 其实就是内存中的一个数据表 代码如下 /// <summary> /// SqlDataReader 生成csv文件 /// </summary> /// <param name="fileNameCsv">文件名(包含文件路径)</param> /// <param name="dr"&g

oracle导出多CSV文件的靠谱的

oracle导出多CSV文件的问题 ---------------------------------------------------------------------- 用ksh脚本从oracle数据库中导出80w数据到csv文件,如用户给定名字为a.csv(文件最大4000行记录),则自动生产文件为a_1.csv,a_2.csv,...., a_200.csv 我已经实现了一个方法,但80w要导5小时,用户没法接受.如下: sqlplus -s user/pwd @${SqlDir}/

PHP将数据库内容转化为csv文件

PHP将数据库内容转化为csv文件,以逗号隔开,为防止数据库内容中含有逗号,影响文件内容显示,需注意添加""(双引号)!!! <?php include "init.php"; $file_name_='file.csv'; $str_content_="aid,username,password,role,status,created_time,updated_time\n"; file_put_contents($file_name_,

淘宝助理导出的csv文件使用的是什么编码,您猜?

今天下午用Java读取从淘宝助理 V4.3 Beta1导出的csv文件,出现中文乱码情况. 一看就是文件编码引起的,不清楚淘宝助理导出的csv文件使用了什么编码,到百度搜索了一下,看到一些相关文章,但测试发现都没有解决这个问题. 最后,我抱着试试看的态度,使用了 utf-16 ,我晕,正常显示中文了. 关于 utf-16 这种编码,这么多看来我还是第一次使用,之前最常用的是 gb2312 和 utf-8 之间的转换. 下面是一个简单的例子: try { DataInputStream in =

R: 导入 csv 文件,导出到csv文件,;绘图后导出为图片、pdf等

################################################### 问题:导入 csv 文件 如何从csv文件中导入数据,?参数怎么设置?常用参数模板是啥? 解决方案: yuan <- read.csv(file = "C:/Users/Administrator/Desktop/test1.csv",header = TRUE,sep = ",",dec = ".", stringsAsFactors

es实战之数据导出成csv文件

从es将数据导出分两步: 查询大量数据 将数据生成文件并下载 本篇主要是将第二步,第一步在<es实战之查询大量数据>中已讲述. csv vs excel excel2003不能超过65536, excel2007及以上版本支持1048576条数据.excel支持的数据量有限,并且生生成文件的速度比较慢. csv具有支持写入量大,文件较小的优点. 故选择csv作为导出文件类型. 导出文件的几种方式: 将数据从es中查询出来,在这个大前提下,对比导出文件的速度. 由前端处理 直接将数据返回给前端,

Vue之将前端的筛选结果导出为csv文件

有导入就有导出哈!这里继导入之后记录一下导出的实现过程. 1.按钮部分: <el-button class="filter-item" style="margin-left: 10px;" type="success" native-type="submit" @click="exportAll()" icon="el-icon-plus"> 导出 </el-butto

Postgresql 将查询结果导出至csv文件

1.将查询结果导入某张表 create table file1( a integer, b character(5) ); insert into file1(a,b) select a,b from view 2.导出 导出之前为防止中文乱码,设置一下数据库编码 set client_encoding='GBK'; 使用copy 命令 执行命令copy file1to '/home/file.csv' with csv header;

将mysql中查询结果导出到csv文件

1.进入mysql:在cmd中输入mysql -u root -p,输入密码: 2.输入查询语句+"into outfile"+文件: select ip from iptable group by ip into outfile 'd:/ip.csv';