1.csv相关

   public static class CsvHelper
{
/// <summary>
/// 根据csv路径获取datatable
/// </summary>
/// <param name="csvPath"></param>
/// <param name="errMsg"></param>
/// <returns></returns>
public static DataTable GetDataTable(string csvPath, out string errMsg)
{
var result = GetDt(csvPath, out errMsg, true);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
return result;
}
private static DataTable GetDt(string csvPath, out string errMsg, bool hasTitle = false)
{
var dt = new DataTable();
try
{
//将数据读入到DataTable中
if (!File.Exists(csvPath))
{
errMsg = "找不到csv文件" + csvPath;
return null;
}
using (StreamReader sr = new StreamReader(csvPath))
{
string line = sr.ReadLine();
if (!string.IsNullOrEmpty(line))
{
var columes = line.Split(',');
//生成列头
for (var i = ; i < columes.Length; i++)
{
var name = "column" + i;
if (hasTitle)
{
var txt = columes[i];
if (!string.IsNullOrWhiteSpace(txt))
{
name = txt;
}
}
while (dt.Columns.Contains(name)) name = name + "_1"; //重复行名称会报错。
dt.Columns.Add(new DataColumn(name, typeof(string)));
} if (!hasTitle)
{
var dr = dt.NewRow();
for (var iCol = ; iCol < columes.Length; iCol++)
{
var range = columes[iCol];
dr[iCol] = range;
}
dt.Rows.Add(dr);
}
line = sr.ReadLine();
//生成行数据
while (!string.IsNullOrWhiteSpace(line))
{
columes = line.Split(',');
var dr = dt.NewRow();
for (var iCol = ; iCol < columes.Length; iCol++)
{
var range = columes[iCol];
dr[iCol] = range;
}
dt.Rows.Add(dr);
line = sr.ReadLine();
}
}
}
errMsg = "";
return dt;
}
catch (Exception ex)
{
LogHelper.Log(ex);
errMsg = ex.Message;
return null;
}
} /// <summary>
/// 将dataTable保存到csv文件
/// </summary>
/// <param name="dt"></param>
/// <param name="csvPath"></param>
/// <param name="errMsg"></param>
/// <returns></returns>
public static bool SaveDataTable(DataTable dt, string csvPath, out string errMsg)
{
var result = SaveDt(dt, csvPath, out errMsg);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
return result;
} private static bool SaveDt(DataTable dt, string csvPath, out string errMsg)
{
try
{
//将数据读入到DataTable中
using (StreamWriter sr = new StreamWriter(csvPath, false, Encoding.Default))
{
var iRowCount = dt.Rows.Count;
var iColCount = dt.Columns.Count;
//生成列头
StringBuilder firstRow = new StringBuilder();
for (var i = ; i < iColCount; i++)
{
firstRow.Append(dt.Columns[i].ColumnName + ",");
}
sr.WriteLine(firstRow.ToString().TrimEnd(','));
for (var iRow = ; iRow < iRowCount; iRow++)
{
StringBuilder otherRow = new StringBuilder();
for (var iCol = ; iCol < iColCount; iCol++)
{
otherRow.Append(dt.Rows[iRow][iCol] + ",");
}
sr.WriteLine(otherRow.ToString().TrimEnd(','));
}
errMsg = "";
return true;
}
}
catch (Exception ex)
{
LogHelper.Log(ex);
errMsg = ex.Message;
return false;
}
}
}

2.datatable相关

  public class DataTableHelper
{ /// <summary>
/// DataTable转化为List集合
/// </summary>
/// <typeparam name="T">实体对象</typeparam>
/// <param name="dt">datatable表</param>
/// <returns>返回list集合</returns>
public static List<T> TableToList<T>(DataTable dt )
{
List<T> list = new List<T>();
Type type = typeof(T);
foreach (DataRow row in dt.Rows)
{
PropertyInfo[] pArray = type.GetProperties(); //集合属性数组
T entity = Activator.CreateInstance<T>(); //新建对象实例
foreach (PropertyInfo p in pArray)
{
if (!dt.Columns.Contains(p.Name) || row[p.Name] == null || row[p.Name] == DBNull.Value)
{
continue; //DataTable列中不存在集合属性或者字段内容为空则,跳出循环,进行下个循环
}
try
{
var obj = Convert.ChangeType(row[p.Name], p.PropertyType);//类型强转,将table字段类型转为集合字段类型
p.SetValue(entity, obj, null);
}
catch (Exception)
{ }
}
list.Add(entity);
}
return list;
} /// <summary>
/// List集合转DataTable
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="list">传入集合</param>
/// <returns>返回datatable结果</returns>
public static DataTable ListToTable<T>(List<T> list )
{
Type tp = typeof(T);
PropertyInfo[] proInfos = tp.GetProperties();
DataTable dt = new DataTable();
foreach (var item in proInfos)
{
dt.Columns.Add(item.Name, typeof(string)); //添加列明及对应类型
}
foreach (var item in list)
{
DataRow dr = dt.NewRow();
foreach (var proInfo in proInfos)
{
object obj = proInfo.GetValue(item,null);
if (obj == null)
{
continue;
}
if ( proInfo.PropertyType == typeof(DateTime) && Convert.ToDateTime(obj) < Convert.ToDateTime("1753-01-01"))
{
continue;
}
dr[proInfo.Name] = obj;
}
dt.Rows.Add(dr);
}
return dt;
}
}

3.excel相关

   public static class ExcelHelper
{
/// <summary>
/// 根据excel路径获取datatable
/// </summary>
/// <param name="excelPath"></param>
/// <param name="errMsg"></param>
/// <returns></returns>
public static DataTable GetDataTable(string excelPath, out string errMsg)
{
var result = GetDt(excelPath, out errMsg, true);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
return result;
}
private static DataTable GetDt(string excelFilePath, out string errMsg, bool hasTitle = false)
{
Microsoft.Office.Interop.Excel.Application app = null;
Microsoft.Office.Interop.Excel._Workbook workbook = null;
var dt = new DataTable();
object oMissiong = System.Reflection.Missing.Value;
try
{
app = new Microsoft.Office.Interop.Excel.Application(); workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong,
oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);
var sheets = workbook.Worksheets; //将数据读入到DataTable中
var worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.Item[]; //读取第一张表
if (worksheet == null)
{
errMsg = "打开excel失败,请确保excel安装环境正确";
return null;
} var iRowCount = worksheet.UsedRange.Rows.Count;
var iColCount = worksheet.UsedRange.Columns.Count;
//生成列头
for (var i = ; i < iColCount; i++)
{
var name = "column" + i;
if (hasTitle)
{
var txt = ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[, i + ]).Text.ToString();
if (!string.IsNullOrWhiteSpace(txt)) name = txt;
}
while (dt.Columns.Contains(name)) name = name + "_1"; //重复行名称会报错。
dt.Columns.Add(new DataColumn(name, typeof(string)));
}
//生成行数据
var rowIdx = hasTitle ? : ;
for (var iRow = rowIdx; iRow <= iRowCount; iRow++)
{
var dr = dt.NewRow();
for (var iCol = ; iCol <= iColCount; iCol++)
{
var range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[iRow, iCol];
dr[iCol - ] = (range.Value2 == null) ? "" : range.Text.ToString();
}
dt.Rows.Add(dr);
}
errMsg = "";
return dt;
}
catch (Exception ex)
{
LogHelper.Log(ex);
errMsg = ex.Message;
return null;
}
finally
{
if (workbook != null)
{
workbook.Close(false, oMissiong, oMissiong);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
}
if (app != null)
{
app.Workbooks.Close();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
}
}
} /// <summary>
/// 将excel保存到文件
/// </summary>
/// <param name="dt"></param>
/// <param name="excelPath"></param>
/// <param name="errMsg"></param>
/// <returns></returns>
public static bool SaveDataTable(DataTable dt, string excelPath, out string errMsg)
{
var result = SaveDt(dt, excelPath, out errMsg);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
return result;
} private static bool SaveDt(DataTable dt, string excelFilePath, out string errMsg)
{
Microsoft.Office.Interop.Excel.Application app = null;
Microsoft.Office.Interop.Excel._Workbook workbook = null;
object oMissiong = System.Reflection.Missing.Value;
try
{
app = new Microsoft.Office.Interop.Excel.Application
{
DisplayAlerts = false
};
workbook = app.Workbooks.Add(true); //将数据读入到DataTable中
var worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.Item[]; //读取第一张表
if (worksheet == null)
{
errMsg = "打开excel失败,请确保excel安装环境正确";
return false;
}
var iRowCount = dt.Rows.Count;
var iColCount = dt.Columns.Count;
//生成列头
for (var i = ; i < iColCount; i++)
{
worksheet.Cells[, i + ] = dt.Columns[i].ColumnName;
}
for (var iRow = ; iRow <= iRowCount; iRow++)
{
for (var iCol = ; iCol <= iColCount; iCol++)
{
worksheet.Cells[iRow, iCol] = dt.Rows[iRow - ][iCol - ].ToString();
}
}
errMsg = "";
return true;
}
catch (Exception ex)
{
LogHelper.Log(ex);
errMsg = ex.Message;
return false;
}
finally
{
if (workbook != null)
{
workbook.Close(true, excelFilePath, oMissiong);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
}
if (app != null)
{
app.Workbooks.Close();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
}
}
}
}

感谢阅读

c#结构体、打他table、excel、csv互转的更多相关文章

  1. 定义结构体和table type

    1: 在se11 中创建结构体 2: 定义一个内表, row type 使用structure类型,将会具有structure的字段. 3:在代码中 使用 结构体和table  type *& ...

  2. B - EXCEL排序(sort+结构体)

    Excel可以对一组纪录按任意指定列排序.现请你编写程序实现类似功能. Input测试输入包含若干测试用例.每个测试用例的第1行包含两个整数 N (<=100000) 和 C,其中 N 是纪录的 ...

  3. Python与C++结构体交互

    需求:根据接口规范,实现与服务端的数据交互 服务端结构体分包头.包体.包尾 包头C++结构体示例如下 typedef struct head { BYTE string1; BYTE string2; ...

  4. oracle函数、包、变量的定义和使用、重点”结构体和数组”

    函数 实例1:输入雇员的姓名,返回该雇员的年薪 create function fun1(spName varchar2) ,); begin +nvl(comm,) into yearSal fro ...

  5. c语言,结构体里面的函数

    以linux-3.2内核代码为例,结构体里面的函数的用法: 例,在某驱动文件中,定义了一个平台设备驱动: static struct platform_driver s3c24xx_led_drive ...

  6. excel==>csv==via phpmyadmin (edit php.ini & my.ini)==> MySQL Database

    正如同标题, 标题的顺序是 先从Excel表单,保存为csv文档. 步骤: 1.这个可以用linux下的libra office打开 abc.xls 2.用libra office 将 abc.xls ...

  7. 5.分析内核中断运行过程,以及中断3大结构体:irq_desc、irq_chip、irqaction

    本节目标:    分析在linux中的中断是如何运行的,以及中断3大结构体:irq_desc.irq_chip.irqaction 在裸板程序中(参考stmdb和ldmia详解): 1.按键按下, 2 ...

  8. Linux进程管理之task_struct结构体

    进程是处于执行期的程序以及它所管理的资源(如打开的文件.挂起的信号.进程状态.地址空间等等)的总称.注意,程序并不是进程,实际上两个或多个进程不仅有可能执行同一程序,而且还有可能共享地址空间等资源. ...

  9. FFMPEG结构体分析:AVCodecContext

    注:写了一系列的结构体的分析的文章,在这里列一个列表: FFMPEG结构体分析:AVFrame FFMPEG结构体分析:AVFormatContext FFMPEG结构体分析:AVCodecConte ...

  10. FFMPEG结构体分析:AVFrame

    注:写了一系列的结构体的分析的文章,在这里列一个列表: FFMPEG结构体分析:AVFrameFFMPEG结构体分析:AVFormatContextFFMPEG结构体分析:AVCodecContext ...

随机推荐

  1. 2017ICPC/广西邀请赛1001(水)HDU6181

    A Math Problem Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)To ...

  2. 解决jsp中编辑和删除时候弹出框闪退的问题。

    ---恢复内容开始--- /* 火箭设备特殊记载</li> <!-- yw4 --> */ function getYw4DL(){ var controlparm={&quo ...

  3. 010 有顺序的Map的实现类:TreeMap和LinkedHashMap

    作者:nnngu GitHub:https://github.com/nnngu 博客园:http://www.cnblogs.com/nnngu 简书:https://www.jianshu.com ...

  4. 手把手教你撸一个 Webpack Loader

    文:小 boy(沪江网校Web前端工程师) 本文原创,转载请注明作者及出处 经常逛 webpack 官网的同学应该会很眼熟上面的图.正如它宣传的一样,webpack 能把左侧各种类型的文件(webpa ...

  5. vim 命令大全 / vi 命令大全

    vim 命令大全 光标控制命令: 命令 光标移动 h 向左移一个字符 j 向下移一行 k 向上移一行 l 向右移一个字符 G 移到文件的最后一行 w 移到下一个字的开头 W 移到下一个字的开头,忽略标 ...

  6. 获取select中的值

    分别使用javascript原生的方法和jquery方法<select id="test" name=""> <option value=&q ...

  7. Angular 4 设置组件样式的几种方式

      你用Angular吗? 一.介绍 如何只改动最简单的css代码,呈现完全不一样的视图效果. 第一种:最基本的设置:   图1 代码 图2 界面运行效果图 平常,想给一个label或者p等标签添加样 ...

  8. CCF系列之数位之和(201512-1)

    试题编号: 201512-1试题名称: 数位之和时间限制: 1.0s内存限制: 256.0MB问题描述: 问题描述 给定一个十进制整数n,输出n的各位数字之和. 输入格式 输入一个整数n. 输出格式 ...

  9. 使用axios post 提交数据,后台获取不到提交的数据解决方案

    一.问题发现 前后端分离使用vue开发,结合axios进行前后端交互数据,一开始使用 get 请求,获取数据,没有发现任何问题,当使用 post请求 传参时,发现,数据明明已经提交,在打开F12 开发 ...

  10. svn checkout The XML response contains invalid XML

    svn checkout 报错:The XML response contains invalid XML 待解决? ---目前没有找到好的解决方法,svn数据库中存的log入手应该可以,有时间再去看 ...