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文件中指 ...
随机推荐
- Scala里面如何使用枚举
枚举通常用来定义已知数量的常量,比如月份,星期,季节等等,用过java的人都知道定义枚举的关键字是enum,在scala里面和java有所不同,来看一个完整的例子定义: object EnumTest ...
- error.jsp错误页面跳转,统一异常处理
常见web项目中会用倒计时然后跳转页面来处理异常 error.jsp关键代码: <script language="javascript" type="text/j ...
- CMFCPropertyGridProperty的使用
设定初始值 CString str(_T("Button")); COleVariant cOlevariant(str); pTypeProperty->SetOrigin ...
- [LeetCode] 161. One Edit Distance_Medium
Given two strings s and t, determine if they are both one edit distance apart. Note: There are 3 pos ...
- 172. Factorial Trailing Zeroes(阶乘中0的个数 数学题)
Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0 Explan ...
- 80. Remove Duplicates from Sorted Array II(双指针)
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twic ...
- CHM无法正常显示的问题
很喜欢看CHM电子书,感觉篇幅不是很长,而且可以索引:但是昨天遇到这个问题: 打开文件的时候发现: 很喜欢看CHM电子书,感觉篇幅不是很长,而且可以索引:但是昨天遇到这个问题: 打开文件的时候发现: ...
- 错误处理:WebForms UnobtrusiveValidationMode 需要“jquery”ScriptResourceMapping
今天在配置用户权限管理的时候,遇到了这么个错误: WebForms UnobtrusiveValidationMode 需要“jquery”ScriptResourceMapping.请添加一个名为 ...
- centos7源码编译安装Subversion 1.9.5
svn是Subversion的简称,是一个开放源代码的版本控制系统.svn有两种运行方式:1.独立服务器(svn://xxx.xxx/xxx) 2.借助apache(http://svn.xxx.xx ...
- DeepMind已将AlphaGo引入多领域 Al泡沫严重
DeepMind已将AlphaGo引入多领域 Al泡沫严重 在稳操胜券的前提下,谷歌旗下的AlphaGo还是向柯洁下了战书.4月10日,由中国围棋协会.浙江省体育局.谷歌三方联合宣布,将于5月23日至 ...