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);
        }
    }
时间: 2024-08-28 08:22:41

C#完美读取CSV的相关文章

Python 读取csv的某行

站长用Python写了一个可以提取csv任一列的代码,欢迎使用.Github链接 csv是Comma-Separated Values的缩写,是用文本文件形式储存的表格数据,比如如下的表格: 就可以存储为csv文件,文件内容是:No.,Name,Age,Score1,Apple,12,982,Ben,13,973,Celia,14,964,Dave,15,95假设上述csv文件保存为"A.csv",如何用Python像操作Excel一样提取其中的一行,也就是一条记录,利用Python自

sparkR读取csv文件

sparkR读取csv文件 The general method for creating SparkDataFrames from data sources is read.df. This method takes in the path for the file to load and the type of data source, and the currently active SparkSession will be used automatically. SparkR suppo

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

对于数百万条数据量的CSV文件,文件大小可能达到数百M,如果简单读取的话很可能出现超时或者卡死的现象. 为了成功将CSV文件里的数据导入数据库,分批处理是非常必要的. 下面这个函数是读取CSV文件中指定的某几行数据: /** * csv_get_lines 读取CSV文件中的某几行数据 * @param $csvfile csv文件路径 * @param $lines 读取行数 * @param $offset 起始行数 * @return array * */ function csv_get

php读取csv文件类

php处理csv文件类: http://www.php100.com/cover/php/540.html <?php define("CSV_Start", 0); define("CSV_Quoted", 1); define("CSV_Quoted2", 2); define("CSV_Unquoted", 3); function readCSV($fh, $len, $delimiter = ',', $enc

读取csv文件,写入oracle数据库

/* * @(#)DataParse.java 2014年4月28日 */ package com.yihaodian.sa.doData; import java.io.BufferedReader;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.sql.Connection;import java.

用程序读取CSV文件的方法

CSV全称 Comma Separated values,是一种用来存储数据的纯文本文件格式,通常用于电子表格或数据库软件.用Excel或者Numbers都可以导出CSV格式的数据. CSV文件的规则 0 开头是不留空,以行为单位.1 可含或不含列名,含列名则居文件第一行. 2 一行数据不垮行,无空行. 3 以半角符号,作分隔符,列为空也要表达其存在. 4 列内容如存在,,则用""包含起来. 5 列内容如存在""则用""""包

本地文件读取(csv,txt)时字符编码问题解决

今天进行csv文件读取时,老是入库为空,因为其中有中文字符,我要通过中文字符映射成相应的编号(上升:1011,下降:1012),于是怎么也取不到编号.刚开始以为程序映射出了问题,最后日志打出来后,发现读取的csv文件内容中文全为乱码.啊啊啊,好坑.于是看了下别人写的读取csv文件的代码,果然是没有设置字符编码.通过字符读取文件,转为字节流一定要进行字符编码设置,否则跑到测试环境或生产环境会使用本地默认字符集,那就坑大了. 问题代码: BufferedReader in = new Buffere

PHP读取csv文件的内容

一次性读取csv文件内所有行的数据 <?php  $file = fopen('windows_2011_s.csv','r');  while ($data = fgetcsv($file)) { //每次读取CSV里面的一行内容 //print_r($data); //此为一个数组,要获得每一个数据,访问数组下标即可 $goods_list[] = $data;  } //print_r($goods_list); /* foreach ($goods_list as $arr){     

R语言读取csv中的内容

1992年,R语言诞生.R语言是PC和Linux时代的产物,R语言和贝尔实验室开发的S语言类似,R支持一系列分析技术,包括统计分析.预测建模.数据可视化.在CRAN上可以找到众多的扩张包. R软件 的首选界面是命令行界面,通过编写脚本来调用相应的功能函数.同时,它也支持图形界面. R语言可以用来做数据挖掘,下面我们就用它来读取birth2.csv 中的内容. //birth2.csv ALGERIA ,36.4,14.6 CONGO ,37.3,8 EGYPT ,42.1,15.3 GHANA