C# 读写csv文件的类
来源:网络来源TAG:读写csv浏览数: 日期:2010-8-9评论:
折叠C# Code复制内容到剪贴板
  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.IO;   
  4. using System.Text;   
  5.   
  6. namespace CSVDemo   
  7. {   
  8.     /// <summary>   
  9.     /// CSVUtil is a helper class handling csv files.   
  10.     /// </summary>   
  11.     public class CSVUtil   
  12.     {   
  13.         private CSVUtil()   
  14.         {   
  15.         }   
  16.         //write a new file, existed file will be overwritten   
  17.         public static void WriteCSV(string filePathName,List<String[]>ls)   
  18.         {   
  19.             WriteCSV(filePathName,false,ls);   
  20.         }   
  21.         //write a file, existed file will be overwritten if append = false   
  22.         public static void WriteCSV(string filePathName,bool append, List<String[]> ls)   
  23.         {   
  24.             StreamWriter fileWriter=new StreamWriter(filePathName,append,Encoding.Default);   
  25.             foreach(String[] strArr in ls)   
  26.             {   
  27.                 fileWriter.WriteLine(String.Join (“,",strArr) );  
  28.             }  
  29.             fileWriter.Flush();  
  30.             fileWriter.Close();  
  31.               
  32.         }  
  33.         public static List<String[]> ReadCSV(string filePathName)  
  34.         {  
  35.             List<String[]> ls = new List<String[]>();  
  36.             StreamReader fileReader=new   StreamReader(filePathName);    
  37.             string strLine="";   
  38.             while (strLine != null)   
  39.             {   
  40.                 strLine = fileReader.ReadLine();   
  41.                 if (strLine != null && strLine.Length>0)   
  42.                 {   
  43.                     ls.Add(strLine.Split(','));   
  44.                     //Debug.WriteLine(strLine);   
  45.                 }   
  46.             }    
  47.             fileReader.Close();   
  48.             return ls;   
  49.         }   
  50.            
  51.     }   
  52. }   
源代码演示了:
1.listview控件,openFileDialog控件的简单运用;
2.autoseed的Random类的使用;
3.保存CSV文件;
4.读取CSV文件;
5.简单的分层思想,视图-listview,业务数据-data,永久数据-csv file
本代码不涉及:
1.listview控件的复杂控制
2.CSV文件内容合法性检验,例如每行是否有相同的列。
Update
2007-12-14  一个不简单的处理csv文件的C#类(库)
http://www.codeproject.com/KB/database/CsvReader.aspx
我没有用过,连下载都没有,因为我用不着,也许某一天会有用。
昨天新闻点击排行
一周新闻点击排行
当月新闻点击排行
新闻链接
上一篇文章:C# 添加文字水印类代码
相关评论
正在加载评论列表...
评论表单加载中...