CSVHelper 导出CSV 格式


public class CSVHelper
{
System.Windows.Forms.SaveFileDialog saveFileDialog1;//保存
private string header = string.Empty;//标题

/// <summary>
/// 初始化打印设置
/// </summary>
/// <param name="printID"></param>
protected void InitExportController(Dictionary<string, object> addition)
{
saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();

saveFileDialog1.Filter = "导出CSV (*.csv)|*.csv";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.CreatePrompt = false;
saveFileDialog1.Title = "导出文件保存路径";
saveFileDialog1.RestoreDirectory = true;//保存对话框是否记忆上次打开的目录

header = addition["HeardTitle"].ToString();
saveFileDialog1.FileName = header;
}

/// <summary>
/// 导出
/// </summary>
/// <param name="dt">表格</param>
/// <param name="strFileName">路径</param>
public bool Export(Dictionary<string, object> addition, System.Data.DataTable dt)
{
if (!object.Equals(dt, null))
{
InitExportController(addition);
try
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string filename = saveFileDialog1.FileName;
return ExportToSvc(addition, dt, filename);
}
}
catch
{
saveFileDialog1.FileName = "请输入文件名称";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string filename = saveFileDialog1.FileName;
return ExportToSvc(addition, dt, filename);
}
}
}

return false;
}

/// <summary>
/// 导出
/// </summary>
/// <param name="gv">内容</param>
/// <param name="strFileName">路径</param>
public bool Export(Dictionary<string, object> addition, DataGridView gv)
{
if (gv.Rows.Count > 0)
{
InitExportController(addition);

try
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string filename = saveFileDialog1.FileName;
return ExportToSvc(addition, gv, filename);
}
}
catch
{
saveFileDialog1.FileName = "请输入文件名称";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string filename = saveFileDialog1.FileName;
return ExportToSvc(addition, gv, filename);
}
}
}
return false;
}

/// <summary>
/// 导出为svc文件,strFileName为要导出的csv格式文件的路径和文件名
/// </summary>
/// <param name="addition">头部信息</param>
/// <param name="dt">表格</param>
/// <param name="strFileName">路径</param>
protected bool ExportToSvc(Dictionary<string, object> addition, System.Data.DataTable dt, string strFileName)
{
string strPath = strFileName;
if (File.Exists(strPath))
{
File.Delete(strPath);
}

//先打印标头
StringBuilder strColu = new StringBuilder();
StringBuilder strValue = new StringBuilder();
int i = 0;
try
{
StreamWriter sw = new StreamWriter(new FileStream(strPath, FileMode.CreateNew), Encoding.GetEncoding("GB2312"));
if (addition.ContainsKey("HeardTitle"))
{
sw.WriteLine(addition["HeardTitle"].ToString());
}

if (addition.ContainsKey("Content"))
{
sw.WriteLine(addition["Content"].ToString());
sw.WriteLine();
}

for (i = 0; i <= dt.Columns.Count - 1; i++)
{
if (addition.ContainsKey(dt.Columns[i].ColumnName))
{
strColu.Append(addition[dt.Columns[i].ColumnName].ToString().Trim());
}
else
{
strColu.Append(dt.Columns[i].ColumnName);
}
strColu.Append(",");
}
strColu.Remove(strColu.Length - 1, 1);//移出掉最后一个,字符

sw.WriteLine(strColu);

foreach (DataRow dr in dt.Rows)
{
strValue.Remove(0, strValue.Length);//移出

for (i = 0; i <= dt.Columns.Count - 1; i++)
{
strValue.Append(dr[i].ToString());
strValue.Append(",");
}
strValue.Remove(strValue.Length - 1, 1);//移出掉最后一个,字符
sw.WriteLine(strValue);
}
if (addition.ContainsKey("Foot"))
{
sw.WriteLine();
sw.WriteLine(addition["Foot"].ToString());
}
sw.Close();
return true;
}
catch (Exception ex)
{
throw ex;
}
}

/// <summary>
/// 导出为svc文件,strFileName为要导出的csv格式文件的路径和文件名
/// </summary>
/// <param name="addition">头部信息</param>
/// <param name="gv">DataGridView控件</param>
/// <param name="strFileName"></param>
protected bool ExportToSvc(Dictionary<string, object> addition, DataGridView gv, string strFileName)
{
string strPath = strFileName;
if (File.Exists(strPath))
{
File.Delete(strPath);
}

//先打印标头
StringBuilder strColu = new StringBuilder();
StringBuilder strValue = new StringBuilder();
int i = 0;
try
{
StreamWriter sw = new StreamWriter(new FileStream(strPath, FileMode.CreateNew), Encoding.GetEncoding("GB2312"));

if (addition.ContainsKey("HeardTitle"))
{
sw.WriteLine(addition["HeardTitle"].ToString());
}

if (addition.ContainsKey("Content"))
{
sw.WriteLine(addition["Content"].ToString());
sw.WriteLine();
}

for (i = 0; i <= gv.Columns.Count - 1; i++)
{
if (gv.Columns[i].Visible == true)
{//可见的列导出,隐藏的列过滤
strColu.Append(gv.Columns[i].HeaderText.Trim());
strColu.Append(",");
}
}
strColu.Remove(strColu.Length - 1, 1);//移出掉最后一个,字符
sw.WriteLine(strColu);

foreach (DataGridViewRow dr in gv.Rows)
{
strValue.Remove(0, strValue.Length);//移出

for (i = 0; i <= gv.Columns.Count - 1; i++)
{
if (gv.Columns[i].Visible == true)
{//可见的导出
strValue.Append(dr.Cells[i].Value.ToString());
strValue.Append(",");
}
}
strValue.Remove(strValue.Length - 1, 1);//移出掉最后一个,字符
sw.WriteLine(strValue);
}

if (addition.ContainsKey("Foot"))
{
sw.WriteLine();
sw.WriteLine(addition["Foot"].ToString());
}

sw.Close();
return true;
}
catch (Exception ex)
{
throw ex;
}
}

/// <summary>
/// 导出CSV
/// </summary>
/// <param name="title">显示标题</param>
/// <param name="name">文件名</param>
/// <param name="dts">一至多个表源</param>
/// <returns></returns>
public bool Export(string title, string name, params DataTable[] dts)
{
bool result = false;
if (dts != null && dts.Length > 0)
{
var dict = new Dictionary<string, object>();
dict["HeardTitle"] = name;
InitExportController(dict);
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
using (StreamWriter sw = new StreamWriter(new FileStream(saveFileDialog1.FileName, FileMode.CreateNew), Encoding.GetEncoding("GB2312")))
{
sw.WriteLine(title);
foreach (DataTable dt in dts)
{
StringBuilder strValue = new StringBuilder();
StringBuilder strColu = new StringBuilder();
for (int i = 0; i <= dt.Columns.Count - 1; i++)
{
strColu.Append(dt.Columns[i].ColumnName);
strColu.Append(",");
}
strColu.Remove(strColu.Length - 1, 1);//移出掉最后一个,字符

sw.WriteLine(strColu);

foreach (DataRow dr in dt.Rows)
{
strValue.Remove(0, strValue.Length);//移出

for (int i = 0; i <= dt.Columns.Count - 1; i++)
{
strValue.Append(dr[i].ToString());
strValue.Append(",");
}
strValue.Remove(strValue.Length - 1, 1);//移出掉最后一个,字符
sw.WriteLine(strValue);
}
sw.WriteLine();
}
}
result = true;
}
catch (Exception exc)
{
Console.WriteLine(exc.Message);
}
}
}
return result;
}
/// <summary>
/// 导出CSV
/// </summary>
/// <param name="title">显示标题</param>
/// <param name="name">文件名</param>
/// <param name="dts">一至多个表源</param>
/// <returns></returns>
public bool Export(string title, string name, DataSet ds)
{
bool result = false;
if (ds != null && ds.Tables.Count > 0)
{
var dict = new Dictionary<string, object>();
dict["HeardTitle"] = name;
InitExportController(dict);
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
using (StreamWriter sw = new StreamWriter(new FileStream(saveFileDialog1.FileName, FileMode.CreateNew), Encoding.GetEncoding("GB2312")))
{
sw.WriteLine(title);
foreach (DataTable dt in ds.Tables)
{
StringBuilder strValue = new StringBuilder();
StringBuilder strColu = new StringBuilder();
for (int i = 0; i <= dt.Columns.Count - 1; i++)
{
strColu.Append(dt.Columns[i].ColumnName);
strColu.Append(",");
}
strColu.Remove(strColu.Length - 1, 1);//移出掉最后一个,字符

sw.WriteLine(strColu);

foreach (DataRow dr in dt.Rows)
{
strValue.Remove(0, strValue.Length);//移出

for (int i = 0; i <= dt.Columns.Count - 1; i++)
{
strValue.Append(dr[i].ToString());
strValue.Append(",");
}
strValue.Remove(strValue.Length - 1, 1);//移出掉最后一个,字符
sw.WriteLine(strValue);
}
sw.WriteLine();
}
}
result = true;
}
catch (Exception exc)
{
Console.WriteLine(exc.Message);
}
}
}
return result;
}
}

CSVHelper 导出CSV 格式,布布扣,bubuko.com

时间: 2024-12-29 05:05:09

CSVHelper 导出CSV 格式的相关文章

Bash中使用MySQL导入导出CSV格式数据[转]

转自: http://codingstandards.iteye.com/blog/604541 MySQL中导出CSV格式数据的SQL语句样本如下: select * from test_info into outfile '/tmp/test.csv' fields terminated by ',' optionally enclosed by '"' escaped by '"' lines terminated by '\r\n'; MySQL中导入CSV格式数据的SQL语句

thinkphp导出csv格式的表格

1 <?php 2 /** 3 * Created by PhpStorm. 4 * User: hanks 5 * Date: 2016/4/20 6 * Time: 13:51 7 */ 8 9 namespace Home\Controller; 10 use Think\Controller; 11 12 class CsvController extends Controller 13 { 14 //导出csv文件 15 private static function put_csv(

我也太牛了,解决了浏览器中,前台导出csv格式,UTF-8编码,且excek打开不乱码!

ExcellentExport.js的方法,利用base64下载文件.支持chrome ,opera,firefox. 于是决定拿来为我所用! 说明一下,这个js的好处是:一句js脚本,就能前台下载,完全无须后台. 但外国人不了解中文的csv用excel打开直接乱码. 但用记事本打开,再直接保存,或另存为ansi都可以让中文不乱码. js里默认应该是utf-8,昨天试了用utf-8转gb2312,失败了! 于是找到这个: utf-8保存的csv格式要让Excel正常打开的话,必须加入在文件最前面

java 导出CSV格式文件 EXCEL打开 防止乱码

package net.joystart.excelTask; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import

excel批量转换为CSV格式,xls批量导出csv格式

工具/原料 excel 2013 地址链接:http://pan.baidu.com/s/1c1ZABlu 密码:d3rc 方法/步骤 首选我们把需要导出为CVS的Excel文件整理集中到一个文件夹中.然后新建一个文件夹用来保存CSV文件的.支持Xlsx.xls格式.   新建一个EXCEL表格,打开后,点击菜单栏上的"开发工具":功能区下点击打开Visual Basic.   如果菜单栏上没有开发工具,则在选项中添加.点击文件,弹出菜单选择选项.在EXCEL选项中,点击自定义功能区,

linux 环境下 mysql 导出CSV格式报表

一般情况下不会特意到linux系统上去使用mysql, 毕竟没有类似MysqlFront这样现成的操作工具.但是产品的线上服务器是linux服务器,没办法,只能硬着头皮码shell语句来操作了. 通用语句如下: mysql -u biadmin -h lbw-52xfj.mysql.rds.aliyuncs.com -p -e "你需要的sql语句" > 文件输出位置 -u 是mysql用户名, -h 是主机地址(如果是在本机上操作可以写 "localhost"

mysql远程快速导出csv格式数据工具

如需转载,请经本人同意. 之前本人曾经写过一个使用 select ....into outfile原理导出数据的脚本,但该脚本值适用于本地快速导出,并不支持远程服务,故又编写了下面这个支持远程导出的脚本.该脚本支持导出文件检测.数据库信息检查.如果大家有好的建议欢迎留言评论.脚本总体而言比较简单,希望对大家有帮助 脚本语言:python 版本:2.7 #!/usr/bin/python # -*- coding:UTF-8 -*- #@author Jane.Hoo #@date 2016/11

mysql导出csv格式去除字段中的\n\r

第一种方法 在导出界面,打开csv自定义选项,勾选 "删除字段中的回车换行符" 选项 phpmyadmin版本是3.4 2.X版本没看到这个选项 第二种方法 UPDATE catalog_product_entity_text SET `value` = REPLACE( REPLACE( `value` , CHAR( 10 ) , '' ) , CHAR( 13 ) , '' ) ; 将数据库字段回车符去掉

php 导出csv格式的文件

使用CI框架写的 public function export_user() { //从session中读取导出条件 $export_info = $this->session->userdata('export_info'); //根据条件查询出结果 $res = $this->search_user($export_info); $filename = date("Y-m-d-H-i-s",time()).".csv"; $fp=fopen(&