写了个类:

 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);
//}
}

最新文章

  1. 无法为目标平台“Microsoft.Data.Tools.Schema.Sql.Sql120DatabaseSchemaProvider”创建扩展管理器
  2. jboss设置图片上传大小
  3. Oracle脚本笔记
  4. UBoot讲解和实践-----------讲解(一)
  5. android webview web里面的数据透传到java以及java的数据透传到web
  6. 【Ural1057】幂和的数量
  7. 值得赞扬的尝试与进步——CSDN开源夏令营第一印象
  8. Dropbox + Farbox高速创建免费博客小站
  9. 文件操作ofstream,open,close,ifstream,fin,依照行来读取数据, fstream,iosin iosout,fio.seekg(),文件写入和文件读写,文件拷贝和文件
  10. 1.2为什么需要public static void main(String[] args)这个方法
  11. golang:高性能消息队列moonmq的简单使用
  12. asp.net Core HttpClient 出现Cannot access a disposed object. Object name: &#39;SocketsHttpHandler&#39; 的问题。
  13. Scrapy爬取伯乐在线文章
  14. 转 java的JsonObject对象提取值
  15. 小白必须懂的MongoDB的十大总结
  16. rabbitmq坑点与异常处理
  17. Lua面向对象之二:类继承
  18. 算法笔记_214:第六届蓝桥杯软件类校赛真题(Java语言A组)
  19. sql游标使用
  20. UNIX基础概念

热门文章

  1. 约束、自定义异常、hashlib模块、logging日志模块
  2. make menuconfig 时出现 mixed implicit and normal rules: deprecated syntax
  3. 2.3 使用ARDUINO控制MC20进行GPRS的TCP通讯
  4. ACM解题之(ZOJ 2212) Argus
  5. iOS Application Project与OS X Application Project对于plist使用的区别
  6. 分布式计算开源框架Hadoop入门实践(二)
  7. 【转】python面向对象中的元类
  8. point-to-point(点对点) 网口
  9. pppoe白皮书
  10. 【Head First Servlets and JSP】笔记9:属性的作用域、线程安全