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 ...
随机推荐
- Bridge Method
1.java编译器采用Bridge Method 来兼容本该使用泛型的地方使用了非泛型的问题. public class TestBridgeMethod { public static void m ...
- CSS中input输入框点击时去掉外边框方法【outline:medium;】----CSS学习
CSS 中添加 outline:medium; JS 控制焦点: $("#CUSTOM_PHONE").focus(function(event){ // this.attr(&q ...
- Python基础(7)_闭包函数、装饰器
一.闭包函数 闭包函数:1.函数内部定义函数,成为内部函数, 2.改内部函数包含对外部作用域,而不是对全局作用域名字的引用那么该内部函数成为闭包函数 #最简单的无参闭包函数 def func1() n ...
- Centos(Yum源更改)
第一步:备份你的原镜像文件,以免出错后可以恢复. [root@openstack yum.repos.d]#mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum. ...
- 【HackerRank】 Filling Jars
Animesh has N empty candy jars, numbered from 1 to N, with infinite capacity. He performs M operatio ...
- JSP笔记04——架构(转)
原始内容:https://www.tutorialspoint.com/struts_2/basic_mvc_architecture.htm Web服务器需要一个JSP引擎,即一个处理JSP页面的容 ...
- P4501 [ZJOI2018]胖
题目 P4501 [ZJOI2018]胖 官方口中的送分题 做法 我们通过手玩(脑补),\(a_i\)所作的贡献(能更新的点)为:在\(a_i\)更新\(\forall x\)更新前前没有其他点能把\ ...
- HMM代码实现
按照网上的代码,自己敲了一下,改了一点点,理解加深了一下. 还有训练HMM的EM算法没看懂,下次接着看: 参考连接:http://www.cnblogs.com/hanahimi/p/4011765. ...
- 【P2422】良好的感觉(单调栈优化DP//奇怪的暴力)
话说正解是单调栈优化DP,然而貌似根据某种玄学的推算,这个题暴力出解貌似也是可以的.首先,我们枚举所有的点作为最小点,然后横向展开,遇到更小的就停止...然后再操作一下,看上去时间O(N^2),然而由 ...
- 基于canvas与原生JS的H5动画引擎
前一段时间项目组里有一些H5动画的需求,由于没有专业的前端人员,便交由我这个做后台的研究相关的H5动画技术. 通过初步调研,H5动画的实现大概有以下几种方式: 1.基于css实现 这种方式比较简单易学 ...