Csharp--Read Csv file to DataTable
在网上找的资料都不怎么好使,许多代码一看就知道根本没有考虑全面。
最后找到一个好用的,在codeproject上,这位老兄写成了一个framework,太重了。
http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader
确实挺好用的。
我没耐下性子看他的实现,自己尝试写了如下的代码来完成了阅读csv.
参照:http://msdn.microsoft.com/en-us/library/ae5bf541%28v=vs.90%29.aspx
只写了两个方法,组织得不是特别优雅。
使用的时候只需要调用ReadCsv2DT即可,传入参数是文件路径和第一行是否是Header的布尔值。
第二个方法是替换CSVWriter封装的多余的双引号。
public static DataTable ReadCsv2DT(string filename,bool isFirstLineHeader)
{
DataTable dt = new DataTable();
int quotecount = ;
int lastbyte = ;
int b = ;
DataRow dr = null;
bool isfirstline = true;
int colindex = ;
List<string> firstlinefields = new List<string>();
StringBuilder sb = new StringBuilder();
using (FileStream fs = File.OpenRead(filename))
{
while ((b = fs.ReadByte()) != -)
{
if (!isfirstline && dr == null)
dr = dt.NewRow();
if (b == && lastbyte == && quotecount % == ) //one row finished
{
if (!isfirstline)
{
dr[colindex] = removeTextQualifier(sb.ToString());
dt.Rows.Add(dr);
}
else
{
if (isFirstLineHeader)
dt.Columns.Add(removeTextQualifier(sb.ToString()));
else firstlinefields.Add(removeTextQualifier(sb.ToString()));
//build the table strucure
if (isfirstline && !isFirstLineHeader)
{
for (int i = ; i <= firstlinefields.Count; i++)
{
dt.Columns.Add("col" + i);
}
dr = dt.NewRow();
for (int j = ; j < firstlinefields.Count; j++)
{
dr[j] = firstlinefields[j];
}
dt.Rows.Add(dr);
}
isfirstline = false;
}
sb.Clear();
quotecount = ;
b = ;
dr = null;
colindex = ;
lastbyte = ;
}
else if (b == && quotecount % == ) //one filed found 44 stand for comma
{
if (isfirstline)
{ if (isFirstLineHeader)
dt.Columns.Add(removeTextQualifier(sb.ToString()));
else
firstlinefields.Add(removeTextQualifier(sb.ToString()));
}
else dr[colindex] =removeTextQualifier(sb.ToString());
sb.Clear();
colindex++;
}
else
{
if (b == ) quotecount++; //"
lastbyte = b;
sb.Append(UnicodeEncoding.ASCII.GetString(new byte[] { byte.Parse(b.ToString()) }));
}
}
};
return dt;
} public static string removeTextQualifier(string text) {
string pattern = "^\"(?<word>[\\s\\S]*?)\"[\r\n]*$";
Regex rgx = new Regex(pattern,RegexOptions.Multiline);
Match m = rgx.Match(text);
if (m.Success)
//return m.Result("($1)").Replace("\"\"", "\"");
return m.Groups["word"].Value.Replace("\"\"", "\"");
else
return text.Replace("\"\"", "\"");
} }
效果图:测试了一个文件,效果还可以,和Excel打开显示的无差异。
如果你需要测试的话,请确保自己写的文件是有效的csv文件,否则请使用excel另存为,自己写的文件改后缀不是真正的csv.
Csharp--Read Csv file to DataTable的更多相关文章
- ogr2ogr: Export Well Known Text (WKT) for one feature to a CSV file
Perhaps you’re looking for this? ogr2ogr -f “CSV” “E:\4_GIS\NorthArkCartoData\UnitedStates\MO_wkt” “ ...
- C# - CSV file reader
// ------------------------------------------------------------------------------------------------- ...
- SQL SERVER – Import CSV File Into SQL Server Using Bulk Insert – Load Comma Delimited File Into SQL Server
CSV stands for Comma Separated Values, sometimes also called Comma Delimited Values. Create TestTabl ...
- [PowerShell Utils] Create a list of virtual machines based on configuration read from a CSV file in Hyper-V
Hello everyone, this is the third post of the series. . Background =============== In my solution, ...
- Qt Read and Write Csv File
This page discusses various available options for working with csv documents in your Qt application. ...
- Python: Write UTF-8 characters to csv file
To use codecs, we can write UTF-8 characters into csv file import codecs with open('ExcelUtf8.csv', ...
- save tracking results into csv file for oxuva long-term tracking dataset (from txt to csv)
save tracking results into csv file for oxuva long-term tracking dataset (from txt to csv) 2019-10-2 ...
- Powercli随笔 - PowerCLI script to sequentially Storage vMotion VMs from a CSV File
PowerCLI script to sequentially Storage vMotion VMs from a CSV File This is a PowerCLI script that I ...
- csharp: datagridview Convert csv file
/// <summary> /// 保存文件 /// 涂聚文 /// 2014-08-29 /// Geovin Du /// </summary> /// <param ...
随机推荐
- 分享一个UI与业务逻辑分层的框架(一)
序言 .NET(C#)的WinForm如何简单易行地进行UI与业务逻辑分层?本系列文章介绍一个WinForm分层框架,该框架针对WinForm中的TextBox,CheckBox,RadioButto ...
- block,inline和inline-block概念和区别
总体概念 block和inline这两个概念是简略的说法,完整确切的说应该是 block-level elements (块级元素) 和 inline elements (内联元素).block元素通 ...
- asp.net mvc4 添加分区出现错误 找到多个与名为“home”的控制器匹配的类型
会出现如下错误”找到多个与名为“home”的控制器匹配的类型“ 在RouteConfig文件中添加命名空间可解决 routes.MapRoute( name: ...
- C#使用iTextSharp给PDF添加水印
代码: /// <summary> /// 添加普通偏转角度文字水印 /// </summary> public static void SetWatermark(string ...
- 微信扫码i支付~官方DEMO的坑
返回目录 之前写过关于微信支付那些坑的文章(<微信JSApi支付~集成到MVC环境后的最后一个坑(网上没有这种解决方案)>,<微信JSApi支付~坑和如何填坑>),下面说一下微 ...
- maven:用appassembler-maven-plugin打包含有自定义目录的JAVA程序
问题说明: 用maven构建了一个项目,目录结构如下: appassemblerd的配置: <plugin> <groupId>org.codehaus.mojo</gr ...
- cocos2dx骨骼动画Armature源码分析(三)
代码目录结构 cocos2dx里骨骼动画代码在cocos -> editor-support -> cocostudio文件夹中,win下通过筛选器,文件结构如下.(mac下没有分,是整个 ...
- initialize和init以及load方法的区别与使用以及什么时候调用
initialize不是init initialize在这个类第一次被调用的时候比如[[class alloc]init]会调用一次initialize方法,不管创建多少次这个类,都只会调用一次这个方 ...
- PHP开发之Zend Studio快捷键汇总
应用场景 快捷键 功能 查看快捷键 ctrl+shift+l 显示所有快捷键列表 查看和修改快捷键 打开Window->Preferences->General->keys 修改字体 ...
- 触屏touchstart 与 click
设计效果:当手指点击或触摸红框线menuList之外的部分时,弹框menuList消失. 问题:在优化触屏版的时候发现如图问题,当menuList弹出,手指触摸屏幕向下滑动时,menuList弹框不消 ...