C#完美读取CSV
/// <summary>
/// 将DataTable中数据写入到CSV文件中
/// </summary>
/// <param name="dt">提供保存数据的DataTable</param>
/// <param name="fileName">CSV的文件路径</param>
public static bool SaveCSV(DataTable dt, string fullPath)
{
try
{
FileInfo fi = new FileInfo(fullPath);
if (!fi.Directory.Exists)
{
fi.Directory.Create();
}
FileStream fs = new FileStream(fullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
//StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
string data = "";
//写出列名称
for (int i = 0; i < dt.Columns.Count; i++)
{
data += "\"" + dt.Columns[i].ColumnName.ToString() + "\"";
if (i < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
//写出各行数据
for (int i = 0; i < dt.Rows.Count; i++)
{
data = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
string str = dt.Rows[i][j].ToString();
str = string.Format("\"{0}\"", str);
data += str;
if (j < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
}
sw.Close();
fs.Close();
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 读取CSV文件到DataTable中
/// </summary>
/// <param name="filePath">CSV的文件路径</param>
/// <returns></returns>
public static DataTable ReadCSV(string filePath)
{
DataTable dt = new DataTable();
int lineNumber = 0;
using (CsvFileReader reader = new CsvFileReader(filePath))
{
CsvRow row = new CsvRow();
while (reader.ReadRow(row))
{ if (0 == lineNumber)
{
foreach (string s in row)
{
dt.Columns.Add(s.Replace("\"", ""));
}
}
else
{
int index = 0;
DataRow dr = dt.NewRow();
foreach (string s in row)
{
dr[index] = s.Replace("\"", "");
index++;
}
dt.Rows.Add(dr);
}
lineNumber++;
}
}
return dt;
}
public class CsvRow : List<string>
{
public string LineText { get; set; }
}
public class CsvFileReader : StreamReader
{
public CsvFileReader(Stream stream)
: base(stream)
{
} public CsvFileReader(string filename)
: base(filename)
{
} /// <summary>
/// Reads a row of data from a CSV file
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
public bool ReadRow(CsvRow row)
{
row.LineText = ReadLine();
if (String.IsNullOrEmpty(row.LineText))
return false; int pos = 0;
int rows = 0; while (pos < row.LineText.Length)
{
string value; // Special handling for quoted field
if (row.LineText[pos] == '"')
{
// Skip initial quote
pos++; // Parse quoted value
int start = pos;
while (pos < row.LineText.Length)
{
// Test for quote character
if (row.LineText[pos] == '"')
{
// Found one
pos++; // If two quotes together, keep one
// Otherwise, indicates end of value
if (pos >= row.LineText.Length || row.LineText[pos] != '"')
{
pos--;
break;
}
}
pos++;
}
value = row.LineText.Substring(start, pos - start);
value = value.Replace("\"\"", "\"");
}
else
{
// Parse unquoted value
int start = pos;
while (pos < row.LineText.Length && row.LineText[pos] != ',')
pos++;
value = row.LineText.Substring(start, pos - start);
} // Add field to list
if (rows < row.Count)
row[rows] = value;
else
row.Add(value);
rows++; // Eat up to and including next comma
while (pos < row.LineText.Length && row.LineText[pos] != ',')
pos++;
if (pos < row.LineText.Length)
pos++;
}
// Delete any unused items
while (row.Count > rows)
row.RemoveAt(rows); // Return true if any columns read
return (row.Count > 0);
}
}
C#完美读取CSV的更多相关文章
- sparkR读取csv文件
sparkR读取csv文件 The general method for creating SparkDataFrames from data sources is read.df. This met ...
- C# 读取 CSV 文件
最近做一个C#项目要导入CSV文件中的数据到Oracle中,使用Aspose.Cells读取中文字段标题却乱码,表的最后多出几行null记录,而且不是免费的,后来找到了NPOI,顾名思义,就是POI的 ...
- PHP读取CSV数据写入数据库
/*读取csv文件*/ public function testCsv(){ $fileName = "tel.csv"; $fp=fopen($fileName,"r& ...
- VB6.0 读取CSV文件
最近做了一个Upload文件的需求,文件的格式为CSV,读取文件的方法整理了一下,如下: 1.先写了一个读取CSV文件的Function: '读取CSV文件 '假设传入的参数strFile=C:\Do ...
- php读取csv文件,在linux上出现中文读取不到的情况 解决方法
今,php读取csv文件,在linux上出现中文读取不到的情况,google,后找到解决办法<?phpsetlocale(LC_ALL, 'zh_CN');$row = 1;$handle = ...
- 内容写到 csv 格式的文件中 及 读取 csv 格式的文件内容
<?php/*把内容写到 csv 格式的文件中 基本思路是:1.用 $fp = fopen("filename", 'mode')打开一个csv文件,可以是打开时才建立的2. ...
- Unity 读取CSV与Excel
前几天看到我们在游戏中需要动态加载某些角色的游戏策划值,关于这个问题怎么解决呢?其实办法很多种,归根到底,就是数据的读取.我们可以想到的存储数据的载体有很多.例如:txt,xml,csv,excel. ...
- 使用univocity-parsers创建和读取csv文件
import com.univocity.parsers.csv.CsvFormat;import com.univocity.parsers.csv.CsvParser;import com.uni ...
- PHP读取CSV大文件导入数据库的示例
对于数百万条数据量的CSV文件,文件大小可能达到数百M,如果简单读取的话很可能出现超时或者卡死的现象. 为了成功将CSV文件里的数据导入数据库,分批处理是非常必要的. 下面这个函数是读取CSV文件中指 ...
随机推荐
- 【Cocos2dx 3.3 Lua】SpriteBatchNode和SpriteFrameCache使用
精灵帧缓存类 一.SpriteFrameCache 精灵帧缓冲类SpriteFrameCache用于存储精灵帧,SpriteFrameCache是一个单例模式,不属于某一个精灵,是所有精灵共享 ...
- soapUI-Groovy Script
1.1.1 Groovy Script soapUI通过以groovy语言编写的脚本来大量支持您的项目. Groovy脚本TestSteps可用于向功能TestCase添加任意功能. 脚本断言用于任 ...
- Lintcode: Hash Function && Summary: Modular Multiplication, Addition, Power && Summary: 长整形long
In data structure Hash, hash function is used to convert a string(or any other type) into an integer ...
- EasyUI写的登录界面
<!DOCTYPE html><html> <head> <meta charset="utf-8" /> ...
- liferay中数据库表的解析未完
页面布局 1:表layout 主要的字段有: 字段 privateLayout 0表示的是公开的页面 字段 layoutId 如果在同一个社区中有很多的界面,layoutId表示各个界面,按照顺序排列 ...
- ftp.GetResponse() 无法连接到远程服务器
最近在做一个ftp上传下载以及在服务器上创建文件夹的工具 报 GetResponse() 无法连接到远程服务器 错误 明明 ip , 账户和 密码 用ftp 工具都能连接上 ,可是 代码就不行了,看 ...
- animation-play-state
animation-play-state: css: .play-state{ -webkit-animation:f1 2s 0.5s infinite linear forwards altern ...
- MySQL从删库到跑路_高级(四)——存储过程
作者:天山老妖S 链接:http://blog.51cto.com/9291927 一.存储过程简介 1.存储过程简介 存储过程是一组具有特定功能的SQl语句集组成的可编程的函数,经编译创建并保存在数 ...
- 用python实现websocket请求遇到的问题及解决方法。
想要实现python的ws库功能,实时获取对方服务器ws协议返回的数据,查了下百度,用如下流程: ws = create_connection("wss://ws.xxxxxxx.info/ ...
- k-means学习笔记
最近看了吴恩达老师的机器学习教程(可以在Coursera,或者网易云课堂上找到)中讲解的k-means聚类算法,k-means是一种应用非常广泛的无监督学习算法,使用比较简单,但其背后的思想是EM算法 ...