封装处理下,以后项目用到可以直接使用,比较简单。

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);

}

}

}

}

}

csv文件与DataTable互相导入处理的更多相关文章

  1. 【SQL Server数据迁移】把csv文件中的数据导入SQL Server的方法

    [sql] view plaincopy --1.修改系统参数 --修改高级参数 sp_configure 'show advanced options',1 go --允许即席分布式查询 sp_co ...

  2. 将CSV文件中的数据导入到SQL Server 数据库中

    导入数据时,需要注意 CSV 文件中的数据是否包含逗号以及双引号,存在时,导入会失败 选择数据库 -> 右键 -> 任务 -> 导入数据 ,然后根据弹出的导入导出向导(如下图)中的提 ...

  3. 一段刚刚出炉的CSV文件转换为DataTable对象的代码

    CSV是以文本形式保存的表格数据,具体是每列数据使用逗号分割,每行数据使用CRLF(\r\n)来结尾,如果数据值包含逗号或CRLF则使用双引号将数值包裹,如果数据值包含双引号则使用两个双引号做为转义. ...

  4. c# 将csv文件转换datatable的两种方式。

    第一种: public static DataTable csvdatatable(string path) { DataTable dt = new DataTable(); string conn ...

  5. MySQL导入含有中文字段(内容)CSV文件乱码解决方法

    特别的注意:一般的CSV文件并不是UTF-8编码,而是10008(MAC-Simplified Chinese GB 2312),所以再通过Navicat导入数据的时候需要指定的编码格式是10008( ...

  6. 解决 Excel 打开 UTF-8 编码 CSV 文件乱码的 BUG

    解决 Excel 打开 UTF-8 编码 CSV 文件乱码的 BUG zoerywzhou@163.com http://www.cnblogs.com/swje/ 作者:Zhouwan 2017-6 ...

  7. excel打开csv文件乱码解决办法

    参考链接: https://jingyan.baidu.com/article/4dc408484776fbc8d846f168.html 问题:用 Excel 打开 csv 文件,确认有乱码的问题. ...

  8. Python 编程快速上手 第十四章 处理 CSV 文件和 JSON 数据

    前言 这一章分为两个部分,处理 CSV 格式的数据和处理 JSON 格式个数据. 处理 CSV 理解 csv csv 的每一行代表了电子表格中的每一行,每个逗号分开两个单元格csv 的内容全部为文本, ...

  9. Excel打开csv文件乱码问题的解决办法

    excel打开csv 出现乱码怎么解决 https://jingyan.baidu.com/article/ac6a9a5e4c681b2b653eacf1.html CSV是逗号分隔值的英文缩写,通 ...

随机推荐

  1. 乳草的入侵//BFS

    P1030 乳草的入侵 时间: 1000ms / 空间: 131072KiB / Java类名: Main 背景 USACO OCT09 6TH 描述 Farmer John一直努力让他的草地充满鲜美 ...

  2. [hackerrank]Even Odd Query

    https://www.hackerrank.com/contests/w5/challenges 简单题,注意整数的0次方是1,奇数. #include <iostream> #incl ...

  3. 【Apache运维基础(1)】Apache的安装与使用

    安装 yum -y install httpd httpd-devel # 在Ubuntu里面叫做Apache2,输入localhost能打开就算成功了 额...当然专业的运维还是老老实实的去编译吧; ...

  4. 非常实用的PHP代码片段推荐

    当使用PHP进行开发的时候,如果你自己收 藏 了一些非常有用的方法或者代码片段,那么将会给你的开发工作带来极大的便利.今天我们将介绍10个超级好用的PHP代码片段,希望大家能够喜欢! 1.  使用te ...

  5. BZOJ2111: [ZJOI2010]Perm 排列计数

    题目:http://www.lydsy.com/JudgeOnline/problem.php?id=2111 题意:一个1,2,...,N的排列P1,P2...,Pn是Magic的,当且仅当2< ...

  6. oracle 11g rac 无法自动启动

    如果以上的操作依然不能使数据库资源自动启动,那么参考下面这篇文章修改资源AUTO_START属性. 查看资源状态: crsctl status resource 资源       -p     crs ...

  7. Tomcat 映射虚拟目录

    设置虚拟目录映射一般有两种用途: (1)把整个web应用映射到tomcat中: 如一个testapp的web应用的路径是/opt/testapp,则通过虚拟目录映射可以将其映射到tomcat(weba ...

  8. UVALive 3661 Animal Run(最短路解最小割)

    题意:动物要逃跑,工作人员要截断从START(左上角)到END(右下角)的道路,每条边权表示拦截该条道路需要多少工作人员.问最少需要多少人才能完成拦截. 通俗地讲,就是把图一分为二所造成消耗的最小值. ...

  9. noip2007提高组题解

    题外话:这一年的noip应该是最受大众关心的,以至于在百度上输入noip第三个关键字就是noip2007.主要是由于这篇文章:http://www.zhihu.com/question/2110727 ...

  10. c & c++中const

    1 const的基本用法 常变量:  const 类型说明符 变量名 #在c语言中,仍是一个变量.c++中则变为一个常量,比如可以设置为数组的长度 常引用:  const 类型说明符 &引用名 ...