首页 技术 正文
技术 2022年11月9日
0 收藏 641 点赞 1,671 浏览 1385 个字
using System.Data;
using System.IO;namespace DotNet.Utilities
{
/// <summary>
/// CSV文件转换类
/// </summary>
public static class CsvHelper
{
/// <summary>
/// 导出报表为Csv
/// </summary>
/// <param name="dt">DataTable</param>
/// <param name="strFilePath">物理路径</param>
/// <param name="tableheader">表头</param>
/// <param name="columname">字段标题,逗号分隔</param>
public static bool dt2csv(DataTable dt, string strFilePath, string tableheader, string columname)
{
try
{
string strBufferLine = "";
StreamWriter strmWriterObj = new StreamWriter(strFilePath, false, System.Text.Encoding.UTF8);
strmWriterObj.WriteLine(tableheader);
strmWriterObj.WriteLine(columname);
for (int i = 0; i < dt.Rows.Count; i++)
{
strBufferLine = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
if (j > 0)
strBufferLine += ",";
strBufferLine += dt.Rows[i][j].ToString();
}
strmWriterObj.WriteLine(strBufferLine);
}
strmWriterObj.Close();
return true;
}
catch
{
return false;
}
} /// <summary>
/// 将Csv读入DataTable
/// </summary>
/// <param name="filePath">csv文件路径</param>
/// <param name="n">表示第n行是字段title,第n+1行是记录开始</param>
public static DataTable csv2dt(string filePath, int n, DataTable dt)
{
StreamReader reader = new StreamReader(filePath, System.Text.Encoding.UTF8, false);
int i = 0, m = 0;
reader.Peek();
while (reader.Peek() > 0)
{
m = m + 1;
string str = reader.ReadLine();
if (m >= n + 1)
{
string[] split = str.Split(','); System.Data.DataRow dr = dt.NewRow();
for (i = 0; i < split.Length; i++)
{
dr[i] = split[i];
}
dt.Rows.Add(dr);
}
}
return dt;
}
}
}//该代码片段来自于: http://www.sharejs.com/codes/csharp/8609
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,077
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,552
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,401
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,176
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,813
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,896