/// <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的更多相关文章

  1. sparkR读取csv文件

    sparkR读取csv文件 The general method for creating SparkDataFrames from data sources is read.df. This met ...

  2. C# 读取 CSV 文件

    最近做一个C#项目要导入CSV文件中的数据到Oracle中,使用Aspose.Cells读取中文字段标题却乱码,表的最后多出几行null记录,而且不是免费的,后来找到了NPOI,顾名思义,就是POI的 ...

  3. PHP读取CSV数据写入数据库

    /*读取csv文件*/ public function testCsv(){ $fileName = "tel.csv"; $fp=fopen($fileName,"r& ...

  4. VB6.0 读取CSV文件

    最近做了一个Upload文件的需求,文件的格式为CSV,读取文件的方法整理了一下,如下: 1.先写了一个读取CSV文件的Function: '读取CSV文件 '假设传入的参数strFile=C:\Do ...

  5. php读取csv文件,在linux上出现中文读取不到的情况 解决方法

    今,php读取csv文件,在linux上出现中文读取不到的情况,google,后找到解决办法<?phpsetlocale(LC_ALL, 'zh_CN');$row = 1;$handle = ...

  6. 内容写到 csv 格式的文件中 及 读取 csv 格式的文件内容

    <?php/*把内容写到 csv 格式的文件中 基本思路是:1.用 $fp = fopen("filename", 'mode')打开一个csv文件,可以是打开时才建立的2. ...

  7. Unity 读取CSV与Excel

    前几天看到我们在游戏中需要动态加载某些角色的游戏策划值,关于这个问题怎么解决呢?其实办法很多种,归根到底,就是数据的读取.我们可以想到的存储数据的载体有很多.例如:txt,xml,csv,excel. ...

  8. 使用univocity-parsers创建和读取csv文件

    import com.univocity.parsers.csv.CsvFormat;import com.univocity.parsers.csv.CsvParser;import com.uni ...

  9. PHP读取CSV大文件导入数据库的示例

    对于数百万条数据量的CSV文件,文件大小可能达到数百M,如果简单读取的话很可能出现超时或者卡死的现象. 为了成功将CSV文件里的数据导入数据库,分批处理是非常必要的. 下面这个函数是读取CSV文件中指 ...

随机推荐

  1. Integer.valueOf方法的源码解读

    public class IntegerDemo { public static void main(String[] args) { Integer i01 = ; ; Integer i03 = ...

  2. js 使用jquery.form.js文件上传

    1.文件上传,使用jquery.form.js插件库 <!DOCTYPE html> <html> <head> <meta charset="UT ...

  3. TCP状态转换图、滑动窗口、半连接状态、2MSL

    一.TCP状态转换图 下图对排除和定位网络或系统故障时大有帮助,也帮助我们更好的编写Linux程序,对嵌入式开发也有指导意义.    先回顾一下TCP建立连接的三次握手过程,以及关闭连接的四次握手过程 ...

  4. JMeter4.0二次开发之导入eclipse

    1.先建立工程,命名为JMeter4.0. JDK版本为10.0.1 2.在官网下载src文件,通过文件系统导入到JMeter4.0工程中 3.在ant中选择download_jars,ant会自动下 ...

  5. 2018-2019-2 20165209 《网络对抗技术》Exp7: 网络欺诈防范

    2018-2019-2 20165209 <网络对抗技术>Exp7: 网络欺诈防范 1 基础问题回答和实验内容 1.1基础问题回答 (1)通常在什么场景下容易受到DNS spoof攻击. ...

  6. JSP禁用缓存常用方法

    内容主要转自:http://www.cnblogs.com/linjiqin/archive/2011/07/20/2111627.html jsp页面禁止缓存设置 1.客户端缓存要在<head ...

  7. MySQL数据库----完整性约束

    一.介绍 约束条件与数据类型的宽度一样,都是可选参数 作用:用于保证数据的完整性和一致性主要分为: PRIMARY KEY (PK) 标识该字段为该表的主键,可以唯一的标识记录 FOREIGN KEY ...

  8. MySQL笔记(三)由txt文件导入数据

    改编自学校实验,涉及一些字符集相关的问题. 索引 建库 导入数据 最终脚本 下载数据 点击这里 建库 create.sql DROP DATABASE IF EXISTS orderdb; CREAT ...

  9. 一个远程启动windows c++程序引发的技术决策现象

    还是因为那个8点半前要启动近百套报盘程序的问题,差不多两周前表示自己会抽空给解决掉,一次性启动,直到昨天才差不多能够抽点时间出来开始想怎么解决的问题. 这个问题的复杂点在于除了启动exe外,还需要鼠标 ...

  10. 20145101 《Java程序设计》第7周学习总结

    20145101<Java程序设计>第7周学习总结 教材学习内容总结 第十二章 Lambda Lambda表达式中this的参考对象以及toString()的接受者,是来自Lambda的周 ...