CSVHelper.cs内容:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Threading;
using System.IO;
using System.Data;
using System.Windows.Forms; namespace IMSCommonFunction
{
public class CSVHelper
{
public static string FilterCSVCell(string cellContent)
{
bool isAddFlag = false;
if (cellContent.IndexOf("\"") != -)
{
cellContent = cellContent.Replace("\"", "\"\"");
cellContent = "\"" + cellContent + "\"";
isAddFlag = true;
}
if (cellContent.IndexOf(",") != - && isAddFlag != true)
{
cellContent = "\"" + cellContent + "\"";
}
return cellContent;
} public static void ExportCSVFile(HttpResponse response, string fullPath, string Content)
{
try
{
response.Buffer = true;
response.Clear();
response.Charset = System.Text.Encoding.Default.BodyName;
response.ContentEncoding = System.Text.Encoding.UTF8;// System.Text.Encoding.GetEncoding("GB2312");//GB2312用Excel打开时,没有乱码。
response.AppendHeader("Content-Disposition", "attachment;filename=" + fullPath);
response.ContentType = "application/ms-excel";
response.Output.Write(Content);
response.Flush();
response.End();
}
catch (ThreadAbortException)
{
}
catch (Exception ex)
{
throw new ApplicationException(string.Format("Export CSV file have a error: {0}", fullPath), ex);
}
} public static void FileDownload(string FullFileName)
{
FileInfo DownloadFile = new FileInfo(FullFileName);
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.ClearHeaders();
System.Web.HttpContext.Current.Response.Buffer = false;
string extension = Path.GetExtension(FullFileName);
extension = string.IsNullOrEmpty(extension) ? extension : extension.ToLower();
switch (extension)
{
case ".xml":
System.Web.HttpContext.Current.Response.ContentType = "text/xml";
break;
default:
System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
break;
}
string browser = System.Web.HttpContext.Current.Request.UserAgent.ToUpper();
bool isNeedEncode = !browser.Contains("FIREFOX");
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" +
(isNeedEncode ? System.Web.HttpUtility.UrlEncode(DownloadFile.Name, System.Text.Encoding.UTF8) : DownloadFile.Name));
System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
System.Web.HttpContext.Current.Response.Flush();
if (System.Web.HttpContext.Current.Response.IsClientConnected)
System.Web.HttpContext.Current.Response.WriteFile(DownloadFile.FullName); //出错
System.Web.HttpContext.Current.Response.End();
System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
} public static void DataHtmlToExcel(HttpResponse response, DataTable dt, string strFileName)
{
string style = @"<style> .text { mso-number-format:\@; } </script> "; //设置格式
//设置Response
response.Clear();
response.Buffer = true;
response.Charset = "utf-8";
response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
//Response.Charset = "utf-8";
if (strFileName.Length > )
{
response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Encoding.UTF8.GetBytes(strFileName)));
}
else
{
response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls");
}
//Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
HttpContext.Current.Response.ContentType = "application/ms-excel"; //绑定数据到DataGrid1
System.Web.UI.WebControls.DataGrid DataGrid1 = new System.Web.UI.WebControls.DataGrid();
DataGrid1.DataSource = dt.DefaultView;
DataGrid1.DataBind();
//将DataGrid1构成的html代码写进StringWriter
//DataGrid1.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid1.RenderControl(hw); response.Write(style);//注意
response.Write(tw.ToString());
response.Flush();
response.End();
} public static void ExportExcel(HttpResponse response, DataTable dt, string filename)
{
try
{
response.Clear();
response.BufferOutput = true;
response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
response.AppendHeader("Content-Disposition", "attachment;filename=" +
HttpUtility.UrlEncode(Encoding.UTF8.GetBytes(filename)));
response.ContentType = "application/ms-excel";
StringBuilder colHeaders = new StringBuilder();
StringBuilder items = new StringBuilder(); DataRow[] dr = dt.Select(); int i = ;
int clength = dt.Columns.Count; for (i = ; i < clength; i++)
{
if (i == clength - )
{
colHeaders.Append(dt.Columns[i].Caption.ToString() + "\n");
}
else
{
colHeaders.Append(dt.Columns[i].Caption.ToString() + "\t");
}
}
response.Write(colHeaders.ToString()); foreach (DataRow row in dr)
{
for (i = ; i < clength; i++)
{
if (i == clength - )
{
items.Append(row[i].ToString() + "\n");
}
else
{
items.Append(row[i].ToString() + "\t");
}
}
}
response.Write(items.ToString());
}
catch (Exception ex)
{
response.Write(ex.Message);
}
finally
{
response.Flush();
response.End();
}
} public static void DataTableToCSV(DataTable table, string file)
{
string title = "";
FileStream fs = new FileStream(file, FileMode.Create);
StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);
for (int i = ; i < table.Columns.Count; i++)
{
title += table.Columns[i].ColumnName + ",";
}
title = title.Substring(, title.Length - ) + "\n";
sw.Write(title);
foreach (DataRow row in table.Rows)
{
string line = "";
for (int i = ; i < table.Columns.Count; i++)
{
line += row[i].ToString() + ",";
}
line = line.Substring(, line.Length - ) + "\n";
sw.Write(line);
}
sw.Close();
fs.Close();
}
}
}

页面后台按钮事件处理:

 protected void btnExportCSV_Click(object sender, EventArgs e)
{
try
{
string sql = Server.UrlDecode(Request["Sql"]);
DataTable dt = Bll.Report.CustomReport.GetCustomReport(sql);
StringBuilder sbHeader = new StringBuilder();
StringBuilder sbContent = new StringBuilder();
DateTime tempDateTime = DateTime.MinValue;
string tempVal = "";
for (int i = , len = dt.Rows.Count; i < len; i++)
{
for (int j = , len2 = dt.Columns.Count; j < len2; j++)
{
if (i == )
{
sbHeader.AppendFormat("{0},", dt.Columns[j].ColumnName);
}
tempVal = dt.Rows[i][j].ToString();
if(DateTime.TryParse(tempVal,out tempDateTime))
tempVal = tempDateTime.ToString("dd-MM-yyyy HH:mm:ss");
sbContent.AppendFormat("{0},", IMSCommonFunction.CSVHelper.FilterCSVCell(tempVal));
}
sbContent.Remove(sbContent.Length - , );
sbContent.AppendLine();
}
sbHeader.Remove(sbHeader.Length - , );
sbHeader.AppendLine();
IMSCommonFunction.CSVHelper.ExportCSVFile(this.Response,
string.Format("CustomReport_{0}.csv", DateTime.Now.ToString("ddMMyyyy_HHmmss")),
sbHeader.ToString() + sbContent.ToString());
}
catch (Exception ex)
{
IMSCommonFunction.SystemEventLog.LogEvent("CustomReport.aspx,export csv file Errormsg", ex, "common", this.CurrentUserId);
this.ShowErrorMsg(ex);
}
}

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

  1. c#将DataTable内容导出为CSV文件

    写了个类: class DataTableAndCSV { public static DataTable csvToDataTable(string file) { string strConn = ...

  2. java导出生成csv文件

    首先我们需要对csv文件有基础的认识,csv文件类似excel,可以使用excel打开,但是csv文件的本质是逗号分隔的,对比如下图: txt中显示: 修改文件后缀为csv后显示如下: 在java中我 ...

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

    今天下午用Java读取从淘宝助理 V4.3 Beta1导出的csv文件,出现中文乱码情况. 一看就是文件编码引起的,不清楚淘宝助理导出的csv文件使用了什么编码,到百度搜索了一下,看到一些相关文章,但 ...

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

    ################################################### 问题:导入 csv 文件 如何从csv文件中导入数据,?参数怎么设置?常用参数模板是啥? 解决方 ...

  5. 如何从sql server导出到csv文件

    如何从sql server导出到csv文件,具体代码如下: private static void WriteHeader(SqlDataReader reader, TextWriter outpu ...

  6. oracle导出多CSV文件的靠谱的

    oracle导出多CSV文件的问题 ---------------------------------------------------------------------- 用ksh脚本从orac ...

  7. 原创 Datareader 导出为csv文件方法

    DataReader 是游标只读数据, 如果是大数据导出,用Datatable 将耗费巨大内存资源.因为Datatable 其实就是内存中的一个数据表 代码如下 /// <summary> ...

  8. 将DataTable内容导出到Excel表格的两种方法

    方法一:循环DataTable单元格内容拼接字符串,利用StreamWriter的Write方法将字符串写入Excel文件中 这种方法很实现很简单.拼接字符串时,每个单元格之间添加'\t'(表示一个占 ...

  9. 导出到CSV文件

    一.手工导出导出 1.winform void DataGridViewToExcel(DataGridView dataGridView1) { SaveFileDialog saveFileDia ...

随机推荐

  1. 基于jQuery自适应宽度跟高度可自定义焦点图

    基于jQuery自适应宽度跟高度可自定义焦点图.这是一款带左右箭头,缩略小图切换的jQuery相册代码.效果图如下: 在线预览   源码下载 实现的代码. html代码: <section cl ...

  2. elasticsearch golang的sdk使用

    文档第一 <elasticsearch权威指南>直接看官网在线版的,比较新,网上那些pdf版的,都是2.x版的,许多不兼容 官方API手册,可以选择版本. golang sdk库的选择 主 ...

  3. APUE信号-程序汇总

    APUE信号-程序汇总      近期重看APUE,发现对于非常多程序的要领还是没有全然理解.所以梳理下便于查看,并且有非常多值得思考的问题. 程序清单10- 1  捕获 SIGUSR1 和 SIGU ...

  4. MEMCACHE分布式算法(PHP)

    //测试分布式算法 $ports = array('端口1', '端口2', '端口3', '端口4', '端口5'); //Memcache端口 $users = array('1000', '10 ...

  5. Linxu

    http://www.92csz.com/study/linux/ MySql 乱码  修改 /etc/my.cnf文件 character-set-server=utf8 , 表名不区分大小写:lo ...

  6. HTTP1.0/1.1/2.0特性对比_转

    转自:HTTP1.0 HTTP1.1 HTTP2.0 主要特性对比  https://segmentfault.com/a/1190000013028798 HTTP1.0 早先1.0的HTTP版本, ...

  7. AR2220 通过cpu-defend policy处理大量大量arp广播的小技巧

    今天发现有局域网里面有几台电脑中毒了,在大量的发送ARP报文,导致设备cpu利用率很高. 一.查看display cpu-defend statistics 发现arp-reply  arp-requ ...

  8. win10用filezilla server搭建ftp服务器一直无法访问

    win10用filezilla server搭建ftp服务器一直无法访问?? 是防火墙导致的,防火墙中允许filezilla server程序的

  9. springcloud配置中心客户端配置遇到的坑

    1. 出错信息如下: 在启动配置中心的客户端时,报以下错误信息: Caused by: java.lang.IllegalArgumentException: Could not resolve pl ...

  10. 微信小程序——引用阿里云字体

    阿里图标官网:http://www.iconfont.cn 使用阿里云图标大致的方法就是:选中你的图标——保存至你的项目——下载你的图标项目——在项目中引用字体文件. 具体方法可以参考:引用阿里云矢量 ...