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文件中指 ...
随机推荐
- python内置函数大全(分类)
python内置函数大全 python内建函数 最近一直在看python的document,打算在基础方面重点看一下python的keyword.Build-in Function.Build-in ...
- python中关于不执行if __name__ == '__main__':测试模块的解决
1.新建测试脚本文件: 2.编辑测试脚本 import unittest import requests import json import HTMLTestRunner ur1 = 'http:/ ...
- 复习一下property
在面向对象程序里,一个对象不要直接访问另一个对象内部的数据.所以我们使用accessor methods来进行对象内部的数据交互. accessor methods(getters and sette ...
- linux命令:linux权限管理命令
权限管理命令 文件的权限只有你两个人可以更改,一个是root,一个是文件所有者. 命令名称:chmod 命令英文原意:change the permissions mode of a file ...
- 【upstream】Nginx配置upstream实现负载均衡
如果Nginx没有仅仅只能代理一台服务器的话,那它也不可能像今天这么火,Nginx可以配置代理多台服务器,当一台服务器宕机之后,仍能保持系统可用.具体配置过程如下: 1. 在http节点下,添加ups ...
- 透过面试题来说说Promise
前言 我们先看看这几个来自大厂的面试题 面试题1: const promise = new Promise(function(resolve,reject){ console.log(1) resol ...
- 全局修改composer源地址
查看 composer 主目录:通过 composer config -l -g 命令可以列出 composer 的全局配置信息,在这些信息中查找 [home] 配置项就是 composer 的主目录 ...
- tfs代码上传到server并下载到新位置
1.svn与git代码管理原理基本一致,基于文档管理,能看到文件代码,通过设置文件的只读属性来控制代码. 而tfs是基于sqlserver及lock来管理,看不见代码文件 2.tfs没有自己的用户管理 ...
- excel输入数字变成特殊符号问题
问题,在单元格里输入数字,结果变成文件夹类型的小图片或特殊符号了,原因是字体为Wingdings,将其设为Times New Roman即可
- 013-安装VNC服务
(1)#001-安装#光盘iso文件安装mount /dev/cdrom /mntcd /mnt/Packagesrpm -ivh tigervnc*rpm -ivh tigervnc按两次tab键 ...