注:对于实体类对象最好新建一个并且继承原有实体类,这样可以将类型进行修改;

方法一:此种方法是用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数据的更多相关文章

  1. oracle创建表空间、创建用户、授权角色和导入导出用户数据

    使用数据库管理员身份登录 -- log as sysdba sqlplus / as sysdba; 创建临时表空间 -- create temporary tablespace create tem ...

  2. Mysql导入导出大量数据的方法、备份恢复办法

    经常使用PHP+Mysql的朋友一般都是通过phpmyadmin来管理数据库的.日常的一些调试开发工作,使用phpmyadmin确实很方便.但是当我们需要导出几百兆甚至几个G的数据库时,phpmyad ...

  3. Oracle sqlldr导入导出txt数据文件详解

    一.sqlldr导入txt 1.预备 a).txt文件 这里要保存成无签名的UTF-8 b).oracle建表 2.编写控制文件input_test.ctl LOAD DATA CHARACTERSE ...

  4. phpmyadmin导入导出大数据文件的办法

    在phpmyadmin的使用中,经常需要进行导入导出数据库的操作. 但是在导入导出大型数据库文件的时候经常会只是部分导出或者部分导入. 或者是导入导出不成功. 原因就是服务器和php.mysql限制了 ...

  5. Oracle使用imp/exop远程导入导出dmp数据

    在导入导出数据之前,习惯性的检查一下,看看我们自己的机器可不可以连接远程的Oracle主机,检测方法是tnsping SERVICE_NAME.我的机器如下: C:\Users\zx>tnspi ...

  6. MySQL mysqldump 导入/导出 结构&数据&存储过程&函数&事件&触发器

    ———————————————-库操作———————————————-1.①导出一个库结构 mysqldump -d dbname -u root -p > xxx.sql ②导出多个库结构 m ...

  7. NPOI导入导出Excel数据

    代码: using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; usi ...

  8. 【Easyexcel】java导入导出超大数据量的xlsx文件 解决方法

    解决方法: 使用easyexcel解决超大数据量的导入导出xlsx文件 easyexcel最大支持行数 1048576. 官网地址: https://alibaba-easyexcel.github. ...

  9. MongoDB导入导出备份数据

    需要提前安装mongodb-database-tools参考:centos离线安装mongodb-database-tools 导出数据 常用的导出有两种:mongodump和mongoexport, ...

随机推荐

  1. github--hello,world(参考官网)

    官网:https://guides.github.com/activities/hello-world/ 一共分为5步. 1.为你的项目新建仓库(repository): 2.新建分支(branch) ...

  2. Java类的装载过程和静态代码块

    在Java中,类装载器把一个类装入Java虚拟机中,要经过三个步骤来完成:装载.连接和初始化,其中连接又可以分成校验.准备和解析三步,除了解析外,其它步骤是严格按照顺序完成的,各个步骤的主要工作如下: ...

  3. 处理jQuery append加入的元素 绑定事件无效的方法

    通过jquery append(或者before.after,一样)新添加进网页的元素,常用的事件不能触发,比如:append了id 为 abc 的元素,那么 $(#abc).click(functi ...

  4. python 标准库 -- glob

    glob glob.glob() import glob l = glob.glob("/root/*") # 返回列表 print l # 输出如下 ['/root/databa ...

  5. 虚拟桌面 VDI

    什么是VDI(Virtual Desktop Infrastructure): 通过对于本企业的服务器进行整合,使用VMware进行虚拟机部署,利用服务器资源,实现由一个物理机实现多个虚拟机,解决资源 ...

  6. 常用JS图片滚动(无缝、平滑、上下左右滚动)代码大全

    innerHTML:    设置或获取位于对象起始和结束标签内的 HTML scrollHeight: 获取对象的滚动高度. scrollLeft:   设置或获取位于对象左边界和窗口中目前可见内容的 ...

  7. JS如何实现真正的对象常量

    前言 众所周知ES6新增的const关键字可以用来声明常量,但是它只对基本数据类型生效(Number.String.Boolean等),那如果我们想声明一个常量对象呢?该如何实现,Object内置对象 ...

  8. bc计算A股上市新股依次涨停股价

    几年的股市可谓惨不忍睹,不提也罢.唯有打新中签的时候,心里稍微有那么一点点的补偿,于是内心就YY可以30板吗,可以40板吗.于是就写了个连板的bc程序,每次中签的时候就运行一下,然后尽情的YY,然而每 ...

  9. maven打包 tomcat运行pom配置 或 打成jar包

    maven打包 tomcat运行pom配置,同时还需要配置org.apache.tomcat.maven插件,这里省略. <groupId>com.company</groupId& ...

  10. zend studio里面这块注释是用什么快捷键按出来的?

    写完类或函数(注意必须写完,不然出现的信息会不完整)后,在其上方空行输入/**,然后回车 /** * * @param string $a * @param string $b * @param st ...