c#将DataTable内容导出为CSV文件
写了个类:
class DataTableAndCSV
{
public static DataTable csvToDataTable(string file)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties='Excel 8.0;'"; // Excel file
if (file.EndsWith(".csv"))
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties='TEXT;HDR=Yes;FMT=Delimited;'"; // csv file:HDR=Yes-- first line is header
//strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='TEXT;HDR=Yes;FMT=Delimited;'"; // csv file:HDR=Yes-- first line is header
OleDbConnection oleConn = new OleDbConnection(strConn);
oleConn.Open();
DataTable sheets = oleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (sheets == null || sheets.Rows.Count < )
{
return null;
}
String fileName = sheets.Rows[]["TABLE_NAME"].ToString(); // sheets.Rows[0] -- first sheet of excel
if (file.EndsWith(".csv"))
fileName = file.Substring(file.LastIndexOf("/"));
string olestr = "select * from [" + fileName + "]";
if (file.EndsWith(".csv"))
olestr = "select * from [" + fileName + "]";
OleDbCommand oleComm = new OleDbCommand(olestr, oleConn);
oleComm.Connection = oleConn;
OleDbDataAdapter oleDa = new OleDbDataAdapter();
oleDa.SelectCommand = oleComm;
DataSet ds = new DataSet();
oleDa.Fill(ds);
oleConn.Close();
return ds.Tables[];
} public static void dataTableToCsv(DataTable table, string file)
{
FileInfo fi = new FileInfo(file);
string path = fi.DirectoryName;
string name = fi.Name;
//\/:*?"<>|
//把文件名和路径分别取出来处理
name = name.Replace(@"\", "\");
name = name.Replace(@"/", "/");
name = name.Replace(@":", ":");
name = name.Replace(@"*", "*");
name = name.Replace(@"?", "?");
name = name.Replace(@"<", "<");
name = name.Replace(@">", ">");
name = name.Replace(@"|", "|");
string title = ""; FileStream fs = new FileStream(path + "\\" + name, 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)
{
if (row.RowState == DataRowState.Deleted) continue;
string line = "";
for (int i = ; i < table.Columns.Count; i++)
{
line += row[i].ToString().Replace(",", "") + ",";
}
line = line.Substring(, line.Length - ) + "\n"; sw.Write(line);
} sw.Close();
fs.Close();
} public static void dataTableToCsv(DataTable table, string file, string Title)
{
FileInfo fi = new FileInfo(file);
string path = fi.DirectoryName;
string name = fi.Name;
//\/:*?"<>|
//把文件名和路径分别取出来处理
name = name.Replace(@"\", "\");
name = name.Replace(@"/", "/");
name = name.Replace(@":", ":");
name = name.Replace(@"*", "*");
name = name.Replace(@"?", "?");
name = name.Replace(@"<", "<");
name = name.Replace(@">", ">");
name = name.Replace(@"|", "|");
string title = ""; FileStream fs = new FileStream(path + "\\" + name, FileMode.Create);
StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default); title += Title + ",";
for (int i = ; i < table.Columns.Count; i++)
{
title += ",";
}
title = title.Substring(, title.Length - ) + "\n";
sw.Write(title);
title = ""; 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)
{
if (row.RowState == DataRowState.Deleted) continue;
string line = "";
for (int i = ; i < table.Columns.Count; i++)
{
line += row[i].ToString().Replace(",", "") + ",";
}
line = line.Substring(, line.Length - ) + "\n"; sw.Write(line);
} sw.Close();
fs.Close();
} //public static void ExportToSvc(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"));
// for (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 (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.Close();
// }
// catch (Exception ex)
// {
// throw ex;
// }
// ////System.Diagnostics.Process.Start(strPath);
//}
}
c#将DataTable内容导出为CSV文件的更多相关文章
- DataTable内容导出为CSV文件
CSVHelper.cs内容: using System; using System.Collections.Generic; using System.Linq; using System.Text ...
- java导出生成csv文件
首先我们需要对csv文件有基础的认识,csv文件类似excel,可以使用excel打开,但是csv文件的本质是逗号分隔的,对比如下图: txt中显示: 修改文件后缀为csv后显示如下: 在java中我 ...
- 淘宝助理导出的csv文件使用的是什么编码,您猜?
今天下午用Java读取从淘宝助理 V4.3 Beta1导出的csv文件,出现中文乱码情况. 一看就是文件编码引起的,不清楚淘宝助理导出的csv文件使用了什么编码,到百度搜索了一下,看到一些相关文章,但 ...
- R: 导入 csv 文件,导出到csv文件,;绘图后导出为图片、pdf等
################################################### 问题:导入 csv 文件 如何从csv文件中导入数据,?参数怎么设置?常用参数模板是啥? 解决方 ...
- 如何从sql server导出到csv文件
如何从sql server导出到csv文件,具体代码如下: private static void WriteHeader(SqlDataReader reader, TextWriter outpu ...
- oracle导出多CSV文件的靠谱的
oracle导出多CSV文件的问题 ---------------------------------------------------------------------- 用ksh脚本从orac ...
- 原创 Datareader 导出为csv文件方法
DataReader 是游标只读数据, 如果是大数据导出,用Datatable 将耗费巨大内存资源.因为Datatable 其实就是内存中的一个数据表 代码如下 /// <summary> ...
- 将DataTable内容导出到Excel表格的两种方法
方法一:循环DataTable单元格内容拼接字符串,利用StreamWriter的Write方法将字符串写入Excel文件中 这种方法很实现很简单.拼接字符串时,每个单元格之间添加'\t'(表示一个占 ...
- 导出到CSV文件
一.手工导出导出 1.winform void DataGridViewToExcel(DataGridView dataGridView1) { SaveFileDialog saveFileDia ...
随机推荐
- python多线程(三)
同步锁 两个需要注意的点: 线程抢的是GIL锁,GIL锁相当于执行权限,拿到执行权限后才能拿到互斥锁Lock,其他线程也可以抢到GIL,但如果发现Lock仍然没有被释放则阻塞,即便是拿到执行权限GIL ...
- MySQL 第六天
回顾 外键: 关联关系(表与表之间: 表中字段指向另外一张表的主键) 外键条件: 字段类型必须一致, 存储引擎必须为innodb 外键约束: 子表约束: 不能插入父表不存在的记录 父表约束: 三种 ...
- POSIX相关概念
POSIX 表示可移植操作系统接口(Portable Operating System Interface ,缩写为 POSIX),POSIX标准定义了操作系统应该为应用程序提供的接口标准,是IEEE ...
- 2.5 使用ARDUINO做主控,手机发送短信控制开关LED
需要准备的硬件 MC20开发板 1个 https://item.taobao.com/item.htm?id=562661881042 GSM/GPRS天线 1根 https://item.taoba ...
- "export" in SHELL
在shell中,若某一变量需要在随后的子程序中运行,则需要以 export 来使变量变成环境变量: export var export的用法总结: 1:一个shell中用export定义的变量,只对当 ...
- Java - 在控制台中执行一个可执行jar
1.Maven打包一个可执行jar: <build> <plugins> <plugin> <groupId>org.apache.maven.plug ...
- assign,copy,retain的区别以及weak和strong的区别
@property (nonatomic, assign) NSString *title; 什么是assign,copy,retain之间的区别? assign: 简单赋值,不更改索 ...
- JQuery Div层滚动条控制(模拟横向滚动条在最顶端显示)
想让DIV层滚动条显示在顶端,CSS样式没找到相关属性,于是用2个DIV层来模拟做了一个.经测试IE浏览器上显示并不太美观!不知道是否还有更好的办法可以实现这功能呢? aaaaaaasssssss ...
- $《第一行代码:Android》读书笔记——第2章 Activity
(一)创建活动 1.创建活动类 创建没有Activity的项目,发现src文件夹是空的,手动创建一个包com.jyj.demo1,在包中添加一个名为MainActivity的class,该MainAc ...
- JAVA 文件转字节数组转字符串
public static void main(String[] args) throws IOException { byte[] bytes = FileUtils.readFileToByteA ...