C#导入导出Excele数据
注:对于实体类对象最好新建一个并且继承原有实体类,这样可以将类型进行修改;
方法一:此种方法是用EPPLUS中的FileInfo流进行读取的(是不是流我还真不太了解,若有懂得请留言,非常感谢了)
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using Abp.Extensions;
- namespace HYZT.Ltxy.International.Ctrip.Exporting
- {
- public class ExcelLib
- {
- public ICtripPolicyExcelImport GetExcel(string filePath)
- {
- if (filePath.Trim() .IsNullOrEmpty())
- throw new Exception("文件名不能为空");
- //因为这儿用得是EPPLUS对Excel进行的操作,所以只能操作
- //2007以后的版本以后的(即扩展名为.xlsx)
- if (!filePath.Trim().EndsWith("xlsx"))
- throw new Exception("请使用office Excel 2007版本或2010版本");
- else if (filePath.Trim().EndsWith("xlsx"))
- {
- ICtripPolicyExcelImport res = new CtripPolicyExcelImport(filePath.Trim());
- return res;
- }
- else return null;
- }
- }
- }
方法接口:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace HYZT.Ltxy.International.Ctrip.Exporting
- {
- public interface ICtripPolicyExcelImport
- {
- /// <summary> 打开文件 </summary>
- bool Open();
- //ExcelVersion Version { get; }
- /// <summary> 文件路径 </summary>
- string FilePath { get; set; }
- /// <summary> 文件是否已经打开 </summary>
- bool IfOpen { get; }
- /// <summary> 文件包含工作表的数量 </summary>
- int SheetCount { get; }
- /// <summary> 当前工作表序号 </summary>
- int CurrentSheetIndex { get; set; }
- /// <summary> 获取当前工作表中行数 </summary>
- int GetRowCount();
- /// <summary> 获取当前工作表中列数 </summary>
- int GetColumnCount();
- /// <summary> 获取当前工作表中某一行中单元格的数量 </summary>
- /// <param name="Row">行序号</param>
- int GetCellCountInRow(int Row);
- /// <summary> 获取当前工作表中某一单元格的值(按字符串返回) </summary>
- /// <param name="Row">行序号</param>
- /// <param name="Col">列序号</param>
- string GetCellValue(int Row, int Col);
- /// <summary> 关闭文件 </summary>
- void Close();
- }
- }
方法实现:
- using OfficeOpenXml;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace HYZT.Ltxy.International.Ctrip.Exporting
- {
- public class CtripPolicyExcelImport:ICtripPolicyExcelImport
- {
- public CtripPolicyExcelImport()
- { }
- public CtripPolicyExcelImport(string path)
- { filePath = path; }
- private string filePath = "";
- private ExcelWorkbook book = null;
- private int sheetCount = ;
- private bool ifOpen = false;
- private int currentSheetIndex = ;
- private ExcelWorksheet currentSheet = null;
- private ExcelPackage ep = null;
- public bool Open()
- {
- try
- {
- ep = new ExcelPackage(new FileInfo(filePath));
- if (ep == null) return false;
- book =ep.Workbook;
- sheetCount = book.Worksheets.Count;
- currentSheetIndex = ;
- currentSheet = book.Worksheets[];
- ifOpen = true;
- }
- catch (Exception ex)
- {
- throw new Exception(ex.Message);
- }
- return true;
- }
- public void Close()
- {
- if (!ifOpen || ep == null) return;
- ep.Dispose();
- }
- //public ExcelVersion Version
- //{ get { return ExcelVersion.Excel07; } }
- public string FilePath
- {
- get { return filePath; }
- set { filePath = value; }
- }
- public bool IfOpen
- { get { return ifOpen; } }
- public int SheetCount
- { get { return sheetCount; } }
- public int CurrentSheetIndex
- {
- get { return currentSheetIndex; }
- set
- {
- if (value != currentSheetIndex)
- {
- if (value >= sheetCount)
- throw new Exception("工作表序号超出范围");
- currentSheetIndex = value;
- currentSheet =book.Worksheets[currentSheetIndex+];
- }
- }
- }
- public int GetRowCount()
- {
- if (currentSheet == null) return ;
- return currentSheet.Dimension.End.Row;
- }
- public int GetColumnCount()
- {
- if (currentSheet == null) return ;
- return currentSheet.Dimension.End.Column;
- }
- public int GetCellCountInRow(int Row)
- {
- if (currentSheet == null) return ;
- if (Row >= currentSheet.Dimension.End.Row) return ;
- return currentSheet.Dimension.End.Column;
- }
- //根据行号和列号获取指定单元格的数据
- public string GetCellValue(int Row, int Col)
- {
- if (currentSheet == null) return "";
- if (Row >= currentSheet.Dimension.End.Row || Col >= currentSheet.Dimension.End.Column) return "";
- object tmpO =currentSheet.GetValue(Row+, Col+);
- if (tmpO == null) return "";
- return tmpO.ToString();
- }
- }
- }
- 方法调用实现功能:
- 1 //用于程序是在本地,所以此时的路径是本地电脑的绝对路劲;
- //当程序发布后此路径应该是服务器上的绝对路径,所以在此之前还要有
- //一项功能是将本地文件上传到服务器上的指定位置,此时在获取路径即可
- public string GetExcelToCtripPolicy(string filePath)
- {
- ExcelLib lib = new ExcelLib();
- if (filePath == null)
- return new ReturnResult<bool>(false, "未找到相应文件");
- string str= tmp.GetCellValue(i, j);
- return str;
- }
方法二:将Excel表格转化成DataTable表,然后在对DataTable进行业务操作
- using Abp.Application.Services;
- using OfficeOpenXml;
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace HYZT.Ltxy.International.Ctrip.GetExcelToDataTable
- {
- public class EPPlusHelperAppService:ApplicationService,IEPPlusHelperAppService
- {
- private static string GetString(object obj)
- {
- try
- {
- return obj.ToString();
- }
- catch (Exception ex)
- {
- return "";
- }
- }
- /// <summary>
- ///将指定的Excel的文件转换成DataTable (Excel的第一个sheet)
- /// </summary>
- /// <param name="fullFielPath">文件的绝对路径</param>
- /// <returns></returns>
- public DataTable WorksheetToTable(string filePath)
- {
- try
- {
- FileInfo existingFile = new FileInfo(filePath);
- ExcelPackage package = new ExcelPackage(existingFile);
- ExcelWorksheet worksheet = package.Workbook.Worksheets[];//选定 指定页
- return WorksheetToTable(worksheet);
- }
- catch (Exception)
- {
- throw;
- }
- }
- /// <summary>
- /// 将worksheet转成datatable
- /// </summary>
- /// <param name="worksheet">待处理的worksheet</param>
- /// <returns>返回处理后的datatable</returns>
- public static DataTable WorksheetToTable(ExcelWorksheet worksheet)
- {
- //获取worksheet的行数
- int rows = worksheet.Dimension.End.Row;
- //获取worksheet的列数
- int cols = worksheet.Dimension.End.Column;
- DataTable dt = new DataTable(worksheet.Name);
- DataRow dr = null;
- for (int i = ; i <= rows; i++)
- {
- if (i > )
- dr = dt.Rows.Add();
- for (int j = ; j <= cols; j++)
- {
- //默认将第一行设置为datatable的标题
- if (i == )
- dt.Columns.Add(GetString(worksheet.Cells[i, j].Value));
- //剩下的写入datatable
- else
- dr[j - ] = GetString(worksheet.Cells[i, j].Value);
- }
- }
- return dt;
- }
- }
- }
之前我有一个程序用的是方法一进行Excel导入的,速度不是很快,后来我又用了第二种方法但是速度更慢了,到底这两种方法哪种快,请大虾指导,还是我用第二种方法的时候业务判断有问题,不得而知,
就请明白人指导我到底这两种方法哪种比较好些;
3:实体类与DataTable之间的互转:
- /// <summary>
- /// DataTable与实体类互相转换
- /// </summary>
- /// <typeparam name="T">实体类</typeparam>
- public class ModelHandler<T> where T : new()
- {
- #region DataTable转换成实体类
- /// <summary>
- /// 填充对象列表:用DataSet的第一个表填充实体类
- /// </summary>
- /// <param name="ds">DataSet</param>
- /// <returns></returns>
- public List<T> FillModel(DataSet ds)
- {
- if (ds == null || ds.Tables[] == null || ds.Tables[].Rows.Count == )
- {
- return null;
- }
- else
- {
- return FillModel(ds.Tables[]);
- }
- }
- /// <summary>
- /// 填充对象列表:用DataSet的第index个表填充实体类
- /// </summary>
- public List<T> FillModel(DataSet ds, int index)
- {
- if (ds == null || ds.Tables.Count <= index || ds.Tables[index].Rows.Count == )
- {
- return null;
- }
- else
- {
- return FillModel(ds.Tables[index]);
- }
- }
- /// <summary>
- /// 填充对象列表:用DataTable填充实体类
- /// </summary>
- public List<T> FillModel(DataTable dt)
- {
- if (dt == null || dt.Rows.Count == )
- {
- return null;
- }
- List<T> modelList = new List<T>();
- foreach (DataRow dr in dt.Rows)
- {
- //T model = (T)Activator.CreateInstance(typeof(T));
- T model = new T();
- for (int i = ; i < dr.Table.Columns.Count; i++)
- {
- PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
- if (propertyInfo != null && dr[i] != DBNull.Value)
- propertyInfo.SetValue(model, dr[i], null);
- }
- modelList.Add(model);
- }
- return modelList;
- }
- /// <summary>
- /// 填充对象:用DataRow填充实体类
- /// </summary>
- public T FillModel(DataRow dr)
- {
- if (dr == null)
- {
- return default(T);
- }
- //T model = (T)Activator.CreateInstance(typeof(T));
- T model = new T();
- for (int i = ; i < dr.Table.Columns.Count; i++)
- {
- PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
- if (propertyInfo != null && dr[i] != DBNull.Value)
- propertyInfo.SetValue(model,dr[i],null);
- }
- return model;
- }
- #endregion
- #region 实体类转换成DataTable
- /// <summary>
- /// 实体类转换成DataSet
- /// </summary>
- /// <param name="modelList">实体类列表</param>
- /// <returns></returns>
- public DataSet FillDataSet(List<T> modelList)
- {
- if (modelList == null || modelList.Count == )
- {
- return null;
- }
- else
- {
- DataSet ds = new DataSet();
- ds.Tables.Add(FillDataTable(modelList));
- return ds;
- }
- }
- /// <summary>
- /// 实体类转换成DataTable
- /// </summary>
- /// <param name="modelList">实体类列表</param>
- /// <returns></returns>
- public DataTable FillDataTable(List<T> modelList)
- {
- if (modelList == null || modelList.Count == )
- {
- return null;
- }
- DataTable dt = CreateData(modelList[]);
- foreach(T model in modelList)
- {
- DataRow dataRow = dt.NewRow();
- foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
- {
- dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null);
- }
- dt.Rows.Add(dataRow);
- }
- return dt;
- }
- /// <summary>
- /// 根据实体类得到表结构
- /// </summary>
- /// <param name="model">实体类</param>
- /// <returns></returns>
- private DataTable CreateData(T model)
- {
- DataTable dataTable = new DataTable(typeof (T).Name);
- foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
- {
- dataTable.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType));
- }
- return dataTable;
- }
- #endregion
- }
3.1:将实体类转化成DataTable之后对DataTable进行操作
- //首先将数据库中查出的数据变成实体类集合,然后将实体类集合转变成DataTable表格
- //dataPercent,然后在对此表格进行操作,表头转化和表格信息
//设置新表的表头:即字段名,有英文改为中文
1 for (int i = ; i < dataPercent.Columns.Count; i++)- {
- DataColumn column = dataPercent.Columns[i];
- string name = column.ColumnName;
- switch (name)
- {
- case "IsDomestic":
- dataPercent.Columns[i].ColumnName = "国内/国际";
- break;
- case "TripType":
- dataPercent.Columns[i].ColumnName = "行程类型";
- break;
- case "GoFlightCode":
- dataPercent.Columns[i].ColumnName = "去程航班号";
- break;
- case "GoCabin":
- dataPercent.Columns[i].ColumnName = "去程舱位";
- break;
- case "GoSeatNum":
- dataPercent.Columns[i].ColumnName = "去程座位数";
- break;
- case "Line":
- dataPercent.Columns[i].ColumnName = "去程行程";
- break;
- case "DepartDate":
- dataPercent.Columns[i].ColumnName = "去程航班日期";
- break;
- case "BackFlightCode":
- dataPercent.Columns[i].ColumnName = "回程航班号";
- break;
- case "BackCabin":
- dataPercent.Columns[i].ColumnName = "回程舱位";
- break;
- case "ReturnDate":
- dataPercent.Columns[i].ColumnName = "回程航班日期";
- break;
- case "BackSeatNum":
- dataPercent.Columns[i].ColumnName = "回程座位数";
- break;
- case "AvCmd":
- dataPercent.Columns[i].ColumnName = "黑屏的AV查询指令";
- break;
- case "State":
- dataPercent.Columns[i].ColumnName = "状态";
- break;
- case "Interval":
- dataPercent.Columns[i].ColumnName = "间隔时间(分钟)";
- break;
- case "Telphone":
- dataPercent.Columns[i].ColumnName = "联系电话";
- break;
- case "Remark":
- dataPercent.Columns[i].ColumnName = "备注";
- break;
- }
- }
- DataTable dtResult = new DataTable();
- //克隆表结构
- dtResult = dataPercent.Clone();
//将克隆的表格进行字段类型的重置,有利于改变表格数据- foreach (DataColumn col in dtResult.Columns)
- {
- if (col.ColumnName == "行程类型" || col.ColumnName == "国内/国际" ||col.ColumnName =="状态")
- {
- //修改列类型
- col.DataType = typeof(String);
- }
- }
- foreach (DataRow row in dataPercent.Rows)
- {
- DataRow rowNew = dtResult.NewRow();
- //rowNew["Id"] = row["Id"];
- rowNew["国内/国际"] = row["国内/国际"] == "true" ? "是" : "否";
- rowNew["行程类型"] = row["行程类型"] == "" ? "单程" : "往返";
- rowNew["去程航班号"] = row["去程航班号"];
- rowNew["去程舱位"] = row["去程舱位"];
- rowNew["去程座位数"] = row["去程座位数"];
- rowNew["去程行程"] = row["去程行程"];
- rowNew["去程航班日期"] = row["去程航班日期"];
- rowNew["回程航班号"] = row["回程航班号"];
- rowNew["回程舱位"] = row["回程舱位"];
- rowNew["回程航班日期"] = row["回程航班日期"];
- rowNew["回程座位数"] = row["回程座位数"];
- rowNew["黑屏的AV查询指令"] = row["黑屏的AV查询指令"];
- //rowNew["创建人Id"] = row["创建人Id"];
- rowNew["状态"] = row["状态"] == "" ? "有效" : "挂起";
- rowNew["间隔时间(分钟)"] = row["间隔时间(分钟)"];
- rowNew["联系电话"] = row["联系电话"];
- rowNew["备注"] = row["备注"];
- dtResult.Rows.Add(rowNew);
- }
C#导入导出Excele数据的更多相关文章
- oracle创建表空间、创建用户、授权角色和导入导出用户数据
使用数据库管理员身份登录 -- log as sysdba sqlplus / as sysdba; 创建临时表空间 -- create temporary tablespace create tem ...
- Mysql导入导出大量数据的方法、备份恢复办法
经常使用PHP+Mysql的朋友一般都是通过phpmyadmin来管理数据库的.日常的一些调试开发工作,使用phpmyadmin确实很方便.但是当我们需要导出几百兆甚至几个G的数据库时,phpmyad ...
- Oracle sqlldr导入导出txt数据文件详解
一.sqlldr导入txt 1.预备 a).txt文件 这里要保存成无签名的UTF-8 b).oracle建表 2.编写控制文件input_test.ctl LOAD DATA CHARACTERSE ...
- phpmyadmin导入导出大数据文件的办法
在phpmyadmin的使用中,经常需要进行导入导出数据库的操作. 但是在导入导出大型数据库文件的时候经常会只是部分导出或者部分导入. 或者是导入导出不成功. 原因就是服务器和php.mysql限制了 ...
- Oracle使用imp/exop远程导入导出dmp数据
在导入导出数据之前,习惯性的检查一下,看看我们自己的机器可不可以连接远程的Oracle主机,检测方法是tnsping SERVICE_NAME.我的机器如下: C:\Users\zx>tnspi ...
- MySQL mysqldump 导入/导出 结构&数据&存储过程&函数&事件&触发器
———————————————-库操作———————————————-1.①导出一个库结构 mysqldump -d dbname -u root -p > xxx.sql ②导出多个库结构 m ...
- NPOI导入导出Excel数据
代码: using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; usi ...
- 【Easyexcel】java导入导出超大数据量的xlsx文件 解决方法
解决方法: 使用easyexcel解决超大数据量的导入导出xlsx文件 easyexcel最大支持行数 1048576. 官网地址: https://alibaba-easyexcel.github. ...
- MongoDB导入导出备份数据
需要提前安装mongodb-database-tools参考:centos离线安装mongodb-database-tools 导出数据 常用的导出有两种:mongodump和mongoexport, ...
随机推荐
- Windows系统前端常用PS快捷键:
1.设置滚轮放大缩小: 编辑--首选项--常规--用滚轮缩放 2.V 移动 ctrl+v 自动选中(图层), 3.M 选框 Shift+M 变换形状 Alt :确定圆形/矩形中心 Shift: 圆形/ ...
- [转] DDD领域驱动设计(三) 之 理论知识收集汇总
最近一直在学习领域驱动设计(DDD)的理论知识,从网上搜集了一些个人认为比较有价值的东西,贴出来和大家分享一下: 我一直觉得不要盲目相信权威,比如不能一谈起领域驱动设计,就一定认为国外的那个Eric ...
- SpringMVC中使用Swagger2整合
Swagger2是什么 Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件. Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 W ...
- JSON总结-持续更新补充
基本的json格式 { "name": "jobs", "boolean": true, "age": null, &q ...
- dubbo 请求调用过程分析
服务消费方发起请求 当服务的消费方引用了某远程服务,服务的应用方在spring的配置实例如下: <dubbo:referenceid="demoService"interfa ...
- Vim按Esc后光标左移问题的解决
参考了这篇文章http://vim.wikia.com/wiki/Prevent_escape_from_moving_the_cursor_one_character_to_the_left 在Vi ...
- js代码风格之链式结构
<div class="box"> <ul class="menu"> <li class="level1"& ...
- Chrome DevTools 调研笔记
1 说明 此篇文章针对Chrome DevTools常用功能进行调研分析.描述了每个功能点能实现的功能.应用场景和详细操作. 2 Elements 2.1 功能 检查和实时更新页面的HTML与C ...
- 一个非常简单的例子告诉你attachEvent和addEventListener的区别
<input id="test" type="button" value="测试"> <script> var te ...
- javaWeb第一天
//第一个JavaWeb项目package com.chy.action; import java.io.IOException; import javax.servlet.ServletExcept ...