c#结构体、打他table、excel、csv互转
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互转的更多相关文章
- 定义结构体和table type
1: 在se11 中创建结构体 2: 定义一个内表, row type 使用structure类型,将会具有structure的字段. 3:在代码中 使用 结构体和table type *& ...
- B - EXCEL排序(sort+结构体)
Excel可以对一组纪录按任意指定列排序.现请你编写程序实现类似功能. Input测试输入包含若干测试用例.每个测试用例的第1行包含两个整数 N (<=100000) 和 C,其中 N 是纪录的 ...
- Python与C++结构体交互
需求:根据接口规范,实现与服务端的数据交互 服务端结构体分包头.包体.包尾 包头C++结构体示例如下 typedef struct head { BYTE string1; BYTE string2; ...
- oracle函数、包、变量的定义和使用、重点”结构体和数组”
函数 实例1:输入雇员的姓名,返回该雇员的年薪 create function fun1(spName varchar2) ,); begin +nvl(comm,) into yearSal fro ...
- c语言,结构体里面的函数
以linux-3.2内核代码为例,结构体里面的函数的用法: 例,在某驱动文件中,定义了一个平台设备驱动: static struct platform_driver s3c24xx_led_drive ...
- excel==>csv==via phpmyadmin (edit php.ini & my.ini)==> MySQL Database
正如同标题, 标题的顺序是 先从Excel表单,保存为csv文档. 步骤: 1.这个可以用linux下的libra office打开 abc.xls 2.用libra office 将 abc.xls ...
- 5.分析内核中断运行过程,以及中断3大结构体:irq_desc、irq_chip、irqaction
本节目标: 分析在linux中的中断是如何运行的,以及中断3大结构体:irq_desc.irq_chip.irqaction 在裸板程序中(参考stmdb和ldmia详解): 1.按键按下, 2 ...
- Linux进程管理之task_struct结构体
进程是处于执行期的程序以及它所管理的资源(如打开的文件.挂起的信号.进程状态.地址空间等等)的总称.注意,程序并不是进程,实际上两个或多个进程不仅有可能执行同一程序,而且还有可能共享地址空间等资源. ...
- FFMPEG结构体分析:AVCodecContext
注:写了一系列的结构体的分析的文章,在这里列一个列表: FFMPEG结构体分析:AVFrame FFMPEG结构体分析:AVFormatContext FFMPEG结构体分析:AVCodecConte ...
- FFMPEG结构体分析:AVFrame
注:写了一系列的结构体的分析的文章,在这里列一个列表: FFMPEG结构体分析:AVFrameFFMPEG结构体分析:AVFormatContextFFMPEG结构体分析:AVCodecContext ...
随机推荐
- cs231n spring 2017 lecture13 Generative Models 听课笔记
1. 非监督学习 监督学习有数据有标签,目的是学习数据和标签之间的映射关系.而无监督学习只有数据,没有标签,目的是学习数据额隐藏结构. 2. 生成模型(Generative Models) 已知训练数 ...
- JavaScript正则表达式验证大全(收集)
以下函数调用方式: ? 1 2 3 4 function check() { var bb = document.getElementById("txt_id").value;// ...
- 关于JAVA实现二维码以及添加二维码LOGO
今天在公司,完成了之前的任务,没有什么事做,就想鼓捣一下二维码,因为之前没有接触过,我就去翻看了几本书,也基本完成了二维码的实现,以及添加二维码的LOGO. 现在绘制二维码一般都使用的是谷歌的zxin ...
- 三 : spring-uploadify上传文件
一 : applicationContext.xml中:必须声明不然获取不到<!-- 上传文件的配置 --> <bean id="multipartResolver&quo ...
- Python 使用 virtualenvwrapper 安装虚拟环境
装载于https://www.jianshu.com/p/9f47a9801329 Python 使用 virtualenvwrapper 安装虚拟环境 Tim_Lee 关注 2017.05.04 2 ...
- 十二个 ASP.NET Core 例子——过滤器
目录: 过滤器介绍 过滤器类别 自定义过滤器和过滤特性 直接短路返回内容 过滤器与中间件的区别 如果要全局日志,不要用过滤器 官方文档传送门 1.过滤器介绍 没有权限直接返回,资源缓存,Action执 ...
- Responder Pro new version could analyze Win10 memory dump
My friend John acquired a memory dump from Windows 10, but he could analyze this memory dump with an ...
- dedecms内容页调用图片集文档的图集图片
2016-8-26 0 条评论 dedecms模板制作 3,209 ℃ 织梦dedecms设置了图片集内容模型的网站栏目文档可以上传图集图片,并提供了单页多图样式.幻灯片样式.多缩略图样式三种表现方式 ...
- windows下github 出现Permission denied (publickey).解决方法
今天在学习github的时候遇到了一些问题,然后爬了一会,找到了解决方法记录下来,以防忘记,当然能帮助别人最好啦! github教科书传送门:http://www.liaoxuefeng.com/wi ...
- 常用 Git 命令清单
http://www.ruanyifeng.com/blog/2015/12/git-cheat-sheet.html 我每天使用 Git ,但是很多命令记不住. 一般来说,日常使用只要记住下图6个命 ...