欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

C#中csv文件与DataTable互相导入处理实例解析

时间:2021-04-01 08:18:40|栏目:.NET代码|点击:

本文介绍了C#中csv文件与DataTable互相导入处理实例解析,主要功能代码封装处理下,相对比较简单。以后项目用到的话可以直接使用。具体方法如下:

1.封装好的类如下:

using System;
using System.Data;
using System.IO;
using System.Text;
using CSharpUtilHelpV2;
using StringUtilHelp;

namespace DBUtilHelpV2Plus
{
  public static class DBToolV2Plus
  {
    /// <summary>
    /// 将DataTable导出到CSV.
    /// </summary>
    /// <param name="table">DataTable</param>
    /// <param name="fullSavePath">保存路径</param>
    /// <param name="tableheader">标题信息</param>
    /// <param name="columname">列名称『eg:姓名,年龄』</param>
    /// <returns>导出成功true;导出失败false</returns>
    public static bool ToCSV(this DataTable table, string fullSavePath, string tableheader, string columname)
    {
      ArgumentChecked(table, fullSavePath);
      //------------------------------------------------------------------------------------
      try
      {
        string _bufferLine = "";
        using (StreamWriter _writerObj = new StreamWriter(fullSavePath, false, Encoding.UTF8))
        {
          if (!string.IsNullOrEmpty(tableheader))
            _writerObj.WriteLine(tableheader);
          if (!string.IsNullOrEmpty(columname))
            _writerObj.WriteLine(columname);
          for (int i = 0; i < table.Rows.Count; i++)
          {
            _bufferLine = "";
            for (int j = 0; j < table.Columns.Count; j++)
            {
              if (j > 0)
                _bufferLine += ",";
              _bufferLine += table.Rows[i][j].ToString();
            }
            _writerObj.WriteLine(_bufferLine);
          }
          return true;
        }
      }
      catch (Exception)
      {
        return false;
      }
    }
    /// <summary>
    /// 参数检查
    /// </summary>
    /// <param name="table"></param>
    /// <param name="fullSavePath"></param>
    private static void ArgumentChecked(DataTable table, string fullSavePath)
    {
      if (table == null)
        throw new ArgumentNullException("table");
      if (string.IsNullOrEmpty(fullSavePath))
        throw new ArgumentNullException("fullSavePath");
      string _fileName = CSharpToolV2.GetFileNameOnly(fullSavePath);
      if (string.IsNullOrEmpty(_fileName))
        throw new ArgumentException(string.Format("参数fullSavePath的值{0},不是正确的文件路径!", fullSavePath));
      if (!_fileName.InvalidFileNameChars())
        throw new ArgumentException(string.Format("参数fullSavePath的值{0},包含非法字符!", fullSavePath));
    }
    /// <summary>
    /// 将CSV文件数据导入到Datable中
    /// </summary>
    /// <param name="table"></param>
    /// <param name="filePath">DataTable</param>
    /// <param name="rowIndex">保存路径</param>
    /// <returns>Datable</returns>
    public static DataTable AppendCSVRecord(this DataTable table, string filePath, int rowIndex)
    {
      ArgumentChecked(table, filePath);
      if (rowIndex < 0)
        throw new ArgumentException("rowIndex");
      using (StreamReader reader = new StreamReader(filePath, Encoding.UTF8, false))
      {
        int i = 0, j = 0;
        reader.Peek();
        while (reader.Peek() > 0)
        {
          j = j + 1;
          string _line = reader.ReadLine();
          if (j >= rowIndex + 1)
          {
            string[] _split = _line.Split(',');
            DataRow _row = table.NewRow();
            for (i = 0; i < _split.Length; i++)
            {
              _row[i] = _split[i];
            }
            table.Rows.Add(_row);
          }
        }
        return table;
      }
    }
  }
}

2.代码使用测试如下:

using System;
using System.Data;
using DBUtilHelpV2;
using DBUtilHelpV2Plus;
namespace DBUtilHelpV2PlusTest
{
  class Program
  {
    static DataTable testDb = null;
    static string fullSavePath = string.Format(@"C:\{0}.csv", DateTime.Now.ToString("yyyyMMddHH"));
    static void Main(string[] args)
    {
      try
      {
        CreateTestDb();
        Console.WriteLine(string.Format("DataTable导出到CSV文件{0}.", testDb.ToCSV(fullSavePath, "姓名,年龄", "人员信息表") == true ? "成功" : "失败"));
        testDb.Rows.Clear();
        Console.WriteLine(string.Format("清空数据,当前{0}条数据.", testDb.Rows.Count));
        testDb = testDb.AppendCSVRecord(fullSavePath, 2);
        Console.WriteLine(string.Format("CSV文件导入到Datable,导入{0}条数据.", testDb.Rows.Count));
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message);
      }
      finally
      {
        Console.ReadLine();
      }
    }
    static void CreateTestDb()
    {
      if (testDb == null)
      {
        testDb = DBToolV2.CreateTable("Name,Age|int");
        for (int i = 1; i <= 10; i++)
        {
          DataRow _row = testDb.NewRow();
          _row["Name"] = string.Format("YanZhiwei_{0}", i);
          _row["Age"] = i;
          testDb.Rows.Add(_row);
        }
      }
    }
  }
}

运行效果如下图所示:

上一篇:C#实现SQL批量插入数据到表的方法

栏    目:.NET代码

下一篇:详解C#开发Android应用程序的流程

本文标题:C#中csv文件与DataTable互相导入处理实例解析

本文地址:http://www.codeinn.net/misctech/92394.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有