博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#完美读取CSV
阅读量:5272 次
发布时间:2019-06-14

本文共 5904 字,大约阅读时间需要 19 分钟。

///         /// 将DataTable中数据写入到CSV文件中        ///         /// 
提供保存数据的DataTable        /// 
CSV的文件路径        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;            }        }        /// 
        /// 读取CSV文件到DataTable中        ///         /// 
CSV的文件路径        /// 
        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
    {        public string LineText { get; set; }    }    public class CsvFileReader : StreamReader    {        public CsvFileReader(Stream stream)            : base(stream)        {        }         public CsvFileReader(string filename)            : base(filename)        {        }         /// 
          /// Reads a row of data from a CSV file          ///           /// 
          /// 
          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);        }    }

转载于:https://www.cnblogs.com/jameslif/p/6117193.html

你可能感兴趣的文章
安装NVIDIA驱动时禁用自带nouveau驱动
查看>>
HDU-1255 覆盖的面积 (扫描线)
查看>>
css3学习01
查看>>
【USACO】 奶牛会展
查看>>
继承和多态
查看>>
Dijkstra+计算几何 POJ 2502 Subway
查看>>
修复IE不能执行JS的方法
查看>>
程序员究竟该如何提高效率zt
查看>>
希尔排序法(缩小增量法)
查看>>
PHP编程基础学习(一)——数据类型
查看>>
MongoDB-JAVA-Driver 3.2版本常用代码全整理(2) - 查询
查看>>
NPOI处理Word文本中上下角标
查看>>
Android笔记 Handler
查看>>
如何阅读大型前端开源项目的源码(转)
查看>>
java.util.Arrays类详解
查看>>
idea搭建tocmat
查看>>
NYOJ-626-intersection set(二分查找)
查看>>
项目管理之路(1):初步踏入项目管理
查看>>
Java 中 静态方法与非静态方法的区别
查看>>
echarts饼图显示百分比
查看>>