C#完美读取CSV
2015-09-08 10:33
585 查看
C#读写CSV,一般情况下根据分隔符(最常用的是逗号分隔符)自动切分
但是特殊情况下,如表中有分隔符的语句,需要特殊解析
对应的文本内容:
测试方法:
原文链接: http://www.codeproject.com/Articles/415732/Reading-and-Writing-CSV-Files-in-Csharp
但是特殊情况下,如表中有分隔符的语句,需要特殊解析
对应的文本内容:
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace ReadWriteCsv { /// <summary> /// Class to store one CSV row /// </summary> public class CsvRow : List<string> { public string LineText { get; set; } } /// <summary> /// Class to write data to a CSV file /// </summary> public class CsvFileWriter : StreamWriter { public CsvFileWriter(Stream stream) : base(stream) { } public CsvFileWriter(string filename) : base(filename) { } /// <summary> /// Writes a single row to a CSV file. /// </summary> /// <param name="row">The row to be written</param> public void WriteRow(CsvRow row) { StringBuilder builder = new StringBuilder(); bool firstColumn = true; foreach (string value in row) { // Add separator if this isn't the first value if (!firstColumn) builder.Append(','); // Implement special handling for values that contain comma or quote // Enclose in quotes and double up any double quotes if (value.IndexOfAny(new char[] { '"', ',' }) != -1) builder.AppendFormat("\"{0}\"", value.Replace("\"", "\"\"")); else builder.Append(value); firstColumn = false; } row.LineText = builder.ToString(); WriteLine(row.LineText); } } /// <summary> /// Class to read data from a CSV file /// </summary> 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); } } }
测试方法:
void WriteTest() { // Write sample data to CSV file using (CsvFileWriter writer = new CsvFileWriter("WriteTest.csv")) { for (int i = 0; i < 100; i++) { CsvRow row = new CsvRow(); for (int j = 0; j < 5; j++) row.Add(String.Format("Column{0}", j)); writer.WriteRow(row); } } } void ReadTest() { // Read sample data from CSV file using (CsvFileReader reader = new CsvFileReader("ReadTest.csv")) { CsvRow row = new CsvRow(); while (reader.ReadRow(row)) { foreach (string s in row) { Console.Write(s); Console.Write(" "); } Console.WriteLine(); } } }
原文链接: http://www.codeproject.com/Articles/415732/Reading-and-Writing-CSV-Files-in-Csharp
相关文章推荐
- C#实现远程开机(局域网测试通过)
- C#实现远程开机(局域网测试通过)
- C#高级----打招呼案例
- C#的async和await
- C#接口类型数组
- C#关键字ref和out
- C#进阶系列——AOP?AOP!
- C# Enum,Int,String的互相转换 枚举转换
- c# 正则表达式笔记
- C# 操作Word知识汇总
- C#笔记整理——用C#创建Windows应用程序
- byte数组本质以及其与其他进制的转换
- CLR via C#
- C# Attribute(特性)之---数据契约 [DataContract]
- C# Attribute(特性)之---数据契约 [DataContract]
- C#的初始化器
- CSharpGL(3)使用CSharpGL.vsix插件
- C#的扩展方法
- 继承和多态
- 【LINQ技术】扩展特性和LINQ操作符