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. POJ 3673 Cow Multiplication

    Cow Multiplication Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 13312   Accepted: 93 ...

  2. 51Nod 1091 线段的重叠(贪心+区间相关,板子题)

    1091 线段的重叠 基准时间限制:1 秒 空间限制:131072 KB 分值: 5         难度:1级算法题 X轴上有N条线段,每条线段包括1个起点和终点.线段的重叠是这样来算的,[10 2 ...

  3. UESTC 1599 wtmsb【优先队列+排序】

    题目链接:UESTC 1599 wtmsb 题意:给你一组数,每一次取出两个最小的数,将这两个数的和放入这组数中,直到这组数只剩下一个,求最后剩下那个数的大小! 分析:比赛的时候首先我就看到这道题数据 ...

  4. BZOJ 2823: [AHOI2012]信号塔

    题目:http://www.lydsy.com/JudgeOnline/problem.php?id=2823 随机增量法.不断加点维护圆,主要是三点共圆那里打得烦(其实也就是个两中垂线求交点+联立方 ...

  5. 通过案例理解position:relative和position:absolute

    w3school过了HTML的知识之后,觉得要自己单纯地去啃知识点有点枯燥,然后自己也很容易忘记,所以便找具体的网站练手便补上不懂的知识点.position:relative和postion:abso ...

  6. [学习OpenCV攻略][009][从摄像机读入数据]

    cvCreateCameraCapture(设备ID) 创建一个摄像机视频,返回值是CvCapture*类型.设备ID表示设备的编号,如果有多个摄像机设备,-1表示随机选择一个设备. #include ...

  7. 基础二 day4 日记

    1.list增删改查 l1 = [1,'alex',True,[1,2,3],(2,3,4),{'name':'alex'}]l1 = ['alex',True,'wusir','ritian','t ...

  8. PHP安全之webshell和后门检测

    基于PHP的应用面临着各种各样的攻击: XSS:对PHP的Web应用而言,跨站脚本是一个易受攻击的点.攻击者可以利用它盗取用户信息.你可以配置Apache,或是写更安全的PHP代码(验证所有用户输入) ...

  9. 什么是命名空间?php命名空间的基本应用分享

    什么是命名空间? php中声明的函数名.类名和常量的名称,在同一次运行中是不能重复的,否则会产生一个致命的错误,常见的解决方法是约定一个前缀.例如 ,在项目开发时,用户 User 模块中的控制器和数据 ...

  10. ECharts插件的使用

    ECharts插件:官网下载echarts.js开发者可以选择源码.下载地址:http://echarts.baidu.com/download.html 下载之后,echarts.js放在js文件夹 ...