[C#]CSVHelper_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > [C#]CSVHelper

[C#]CSVHelper

 2014/10/30 3:19:22  楚人游子  程序员俱乐部  我要评论(0)
  • 摘要:关键代码:usingSystem.Data;usingSystem.IO;usingSystem.Text;namespaceYanZhiwei.DotNet2.Utilities.Common{///<summary>///CSV文件转换类///</summary>publicstaticclassCSVHelper{#region导出到csv文件///<summary>///导出到csv文件///eg:///CSVHelper.ToCSV
  • 标签:C#

关键代码:

class="csharpcode">using System.Data;
using System.IO;
using System.Text;

namespace YanZhiwei.DotNet2.Utilities.Common
{
    /// <summary>
    /// CSV文件转换类
    /// </summary>
    public static class CSVHelper
    {
        #region 导出到csv文件
        /// <summary>
        /// 导出到csv文件
        /// eg:
        /// CSVHelper.ToCSV(_personInfoView, @"C:\Users\YanZh_000\Downloads\person.csv", "用户信息表", "名称,年龄");
        /// </summary>
        /// <param name="table">DataTable</param>
        /// <param name="filePath">导出路径</param>
        /// <param name="tableheader">标题</param>
        /// <param name="columname">列名称,以','英文逗号分隔</param>
        /// <returns>是否导出成功</returns>
        public static bool ToCSV(this DataTable table, string filePath, string tableheader, string columname)
        {
            try
            {
                if (File.Exists(filePath))
                    File.Delete(filePath);
                using (FileStream _stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
                {
                    StreamWriter _writer = new StreamWriter(_stream, Encoding.UTF8);
                    _writer.WriteLine(tableheader);
                    _writer.WriteLine(columname);
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        for (int j = 0; j < table.Columns.Count; j++)
                        {
                            _writer.Write(table.Rows[i][j].ToString());
                            _writer.Write(",");
                        }
                        _writer.WriteLine();
                    }
                    _writer.Close();
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }
        #endregion
        #region  将CSV文件导入到DataTable
        /// <summary>
        /// 将CSV文件导入到DataTable
        /// </summary>
        /// <param name="table">DataTable</param>
        /// <param name="filePath">csv文件物理路径</param>
        /// <param name="startRowIndex">数据导入起始行号</param>
        /// <returns>DataTable</returns>
        public static DataTable ImportToTable(this DataTable table, string filePath, int startRowIndex)
        {
            using (StreamReader reader = new StreamReader(filePath, Encoding.UTF8, false))
            {
                int j = 0;
                while (reader.Peek() > -1)
                {
                    j = j + 1;
                    string _line = reader.ReadLine();
                    if (j >= startRowIndex + 1)
                    {
                        string[] _dataArray = _line.Split(',');
                        DataRow _dataRow = table.NewRow();
                        for (int k = 0; k < table.Columns.Count; k++)
                        {
                            _dataRow[k] = _dataArray[k];
                        }
                        table.Rows.Add(_dataRow);
                    }
                }
                return table;
            }
        }
        #endregion
    }
}

测试代码:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Data;
using YanZhiwei.DotNet2.UtilitiesTests;
namespace YanZhiwei.DotNet2.Utilities.Common.Tests
{
    [TestClass()]
    public class CSVHelperTests
    {
        private DataTable TestTable;
        [TestMethod()]
        public void ToCSVTest()
        {
            for (Int16 i = 18; i < 28; i++)
            {
                DataRow _person = TestTable.NewRow();
                _person["Name"] = "YanZhiwei" + i;
                _person["Age"] = i;
                TestTable.Rows.Add(_person);
            }
            bool _expected = true;
            bool _actual = CSVHelper.ToCSV(TestTable, @"C:\Users\YanZh_000\Downloads\person.csv", "用户信息表", "名称,年龄");
            Assert.AreEqual(_expected, _actual);
        }
        [TestInitialize]
        public void InitTestTable()
        {
            TestTable = new DataTable();
            TestTable.Columns.Add(new DataColumn("Name", typeof(string)));
            TestTable.Columns.Add(new DataColumn("Age", typeof(int)));
        }

        [TestMethod()]
        public void ImportToTableTest()
        {
            DataTable _personInfoView = TestTable.Clone();
            DataTable _expected = TestTable.Clone();
            for (Int16 i = 18; i < 28; i++)
            {
                DataRow _person = _expected.NewRow();
                _person["Name"] = "YanZhiwei" + i;
                _person["Age"] = i;
                _expected.Rows.Add(_person);
            }
            DataTable _actual = CSVHelper.ImportToTable(_personInfoView, @"C:\Users\YanZh_000\Downloads\person.csv", 2);
            Assert.IsTrue(ResultSetComparer.AreIdenticalResultSets(_expected, _actual));
        }
        [TestCleanup]
        public void ResetTable()
        {
            TestTable = null;
        }
    }
}

测试结果:

image

发表评论
用户名: 匿名