• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >C#教程 > C#中csv文件与DataTable互相导入处理实例解析

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

作者: 字体:[增加 减小] 来源:互联网 时间:2017-05-28

通过本文主要向大家介绍了c datatable 保存csv,c#读取csv文件,c#读取csv,c#导出csv文件,c#导出csv等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

本文介绍了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;
      }
    }
  }
}
</div>

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);
        }
      }
    }
  }
}
</div>

运行效果如下图所示:

</div>
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • C#中将DataTable转换成CSV文件的方法
  • C#中csv文件与DataTable互相导入处理实例解析

相关文章

  • 2017-05-28httpwebreqeust读取httponly的cookie方法
  • 2017-05-28C# 图片与二进制转换的简单实例
  • 2017-05-28基于C# winform实现图片上传功能的方法
  • 2017-05-28c# 正则指引--字符组
  • 2017-05-28C#默认双缓冲技术实例分析
  • 2017-05-28C# 泛型参数转换
  • 2017-05-28浅谈二叉查找树的集合总结分析
  • 2017-05-28openfiledialog读取txt写入数据库示例
  • 2017-05-28解析数字签名的substring结构(获取数字签名时间)
  • 2017-05-28C#语法相比其它语言比较独特的地方(三)

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • C#导出文本内容到word文档的方法
    • 在C#中global关键字的作用及其用法
    • C#获取ListView鼠标下的Item实例
    • C#创建数据库及导入sql脚本的方法
    • 简单实现C#异步操作
    • c# Graphics使用方法(画圆写字代码)
    • C#语言基础——结构体和枚举类型全面解析
    • C# IEnumerable和IEnumerator接口浅析
    • C#中的正则表达式介绍
    • Visual C#类的定义及实现方法实例解析

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有