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

方法一:此种方法是用EPPLUS中的FileInfo流进行读取的(是不是流我还真不太了解,若有懂得请留言,非常感谢了)

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Abp.Extensions;
  7.  
  8. namespace HYZT.Ltxy.International.Ctrip.Exporting
  9. {
  10. public class ExcelLib
  11. {
  12. public ICtripPolicyExcelImport GetExcel(string filePath)
  13. {
  14. if (filePath.Trim() .IsNullOrEmpty())
  15. throw new Exception("文件名不能为空");
  16. //因为这儿用得是EPPLUS对Excel进行的操作,所以只能操作
  17. //2007以后的版本以后的(即扩展名为.xlsx)
  18. if (!filePath.Trim().EndsWith("xlsx"))
  19. throw new Exception("请使用office Excel 2007版本或2010版本");
  20.  
  21. else if (filePath.Trim().EndsWith("xlsx"))
  22. {
  23. ICtripPolicyExcelImport res = new CtripPolicyExcelImport(filePath.Trim());
  24. return res;
  25. }
  26. else return null;
  27. }
  28. }
  29. }

方法接口:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace HYZT.Ltxy.International.Ctrip.Exporting
  8. {
  9. public interface ICtripPolicyExcelImport
  10. {
  11. /// <summary> 打开文件 </summary>
  12. bool Open();
  13. //ExcelVersion Version { get; }
  14. /// <summary> 文件路径 </summary>
  15. string FilePath { get; set; }
  16. /// <summary> 文件是否已经打开 </summary>
  17. bool IfOpen { get; }
  18. /// <summary> 文件包含工作表的数量 </summary>
  19. int SheetCount { get; }
  20. /// <summary> 当前工作表序号 </summary>
  21. int CurrentSheetIndex { get; set; }
  22. /// <summary> 获取当前工作表中行数 </summary>
  23. int GetRowCount();
  24. /// <summary> 获取当前工作表中列数 </summary>
  25. int GetColumnCount();
  26. /// <summary> 获取当前工作表中某一行中单元格的数量 </summary>
  27. /// <param name="Row">行序号</param>
  28. int GetCellCountInRow(int Row);
  29. /// <summary> 获取当前工作表中某一单元格的值(按字符串返回) </summary>
  30. /// <param name="Row">行序号</param>
  31. /// <param name="Col">列序号</param>
  32. string GetCellValue(int Row, int Col);
  33. /// <summary> 关闭文件 </summary>
  34. void Close();
  35. }
  36. }

方法实现:

  1. using OfficeOpenXml;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8.  
  9. namespace HYZT.Ltxy.International.Ctrip.Exporting
  10. {
  11. public class CtripPolicyExcelImport:ICtripPolicyExcelImport
  12. {
  13.  
  14. public CtripPolicyExcelImport()
  15. { }
  16.  
  17. public CtripPolicyExcelImport(string path)
  18. { filePath = path; }
  19.  
  20. private string filePath = "";
  21. private ExcelWorkbook book = null;
  22. private int sheetCount = ;
  23. private bool ifOpen = false;
  24. private int currentSheetIndex = ;
  25. private ExcelWorksheet currentSheet = null;
  26. private ExcelPackage ep = null;
  27.  
  28. public bool Open()
  29. {
  30. try
  31. {
  32. ep = new ExcelPackage(new FileInfo(filePath));
  33.  
  34. if (ep == null) return false;
  35. book =ep.Workbook;
  36. sheetCount = book.Worksheets.Count;
  37. currentSheetIndex = ;
  38. currentSheet = book.Worksheets[];
  39. ifOpen = true;
  40. }
  41. catch (Exception ex)
  42. {
  43. throw new Exception(ex.Message);
  44. }
  45. return true;
  46. }
  47.  
  48. public void Close()
  49. {
  50. if (!ifOpen || ep == null) return;
  51. ep.Dispose();
  52. }
  53.  
  54. //public ExcelVersion Version
  55. //{ get { return ExcelVersion.Excel07; } }
  56.  
  57. public string FilePath
  58. {
  59. get { return filePath; }
  60. set { filePath = value; }
  61. }
  62.  
  63. public bool IfOpen
  64. { get { return ifOpen; } }
  65.  
  66. public int SheetCount
  67. { get { return sheetCount; } }
  68.  
  69. public int CurrentSheetIndex
  70. {
  71. get { return currentSheetIndex; }
  72. set
  73. {
  74. if (value != currentSheetIndex)
  75. {
  76. if (value >= sheetCount)
  77. throw new Exception("工作表序号超出范围");
  78. currentSheetIndex = value;
  79. currentSheet =book.Worksheets[currentSheetIndex+];
  80. }
  81. }
  82. }
  83.  
  84. public int GetRowCount()
  85. {
  86. if (currentSheet == null) return ;
  87. return currentSheet.Dimension.End.Row;
  88. }
  89.  
  90. public int GetColumnCount()
  91. {
  92. if (currentSheet == null) return ;
  93. return currentSheet.Dimension.End.Column;
  94. }
  95.  
  96. public int GetCellCountInRow(int Row)
  97. {
  98. if (currentSheet == null) return ;
  99. if (Row >= currentSheet.Dimension.End.Row) return ;
  100. return currentSheet.Dimension.End.Column;
  101. }
  102. //根据行号和列号获取指定单元格的数据
  103. public string GetCellValue(int Row, int Col)
  104. {
  105. if (currentSheet == null) return "";
  106. if (Row >= currentSheet.Dimension.End.Row || Col >= currentSheet.Dimension.End.Column) return "";
  107. object tmpO =currentSheet.GetValue(Row+, Col+);
  108. if (tmpO == null) return "";
  109. return tmpO.ToString();
  110. }
  111. }
  112. }
  1. 方法调用实现功能:
  2.  
  3. 1 //用于程序是在本地,所以此时的路径是本地电脑的绝对路劲;
  4. //当程序发布后此路径应该是服务器上的绝对路径,所以在此之前还要有
  5. //一项功能是将本地文件上传到服务器上的指定位置,此时在获取路径即可
  6. public string GetExcelToCtripPolicy(string filePath)
  7. {
  8. ExcelLib lib = new ExcelLib();
  9. if (filePath == null)
  10. return new ReturnResult<bool>(false, "未找到相应文件");
  11. string str= tmp.GetCellValue(i, j);
  12. return str;
  13. }

方法二:将Excel表格转化成DataTable表,然后在对DataTable进行业务操作

  1. using Abp.Application.Services;
  2. using OfficeOpenXml;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10.  
  11. namespace HYZT.Ltxy.International.Ctrip.GetExcelToDataTable
  12. {
  13. public class EPPlusHelperAppService:ApplicationService,IEPPlusHelperAppService
  14. {
  15. private static string GetString(object obj)
  16. {
  17. try
  18. {
  19. return obj.ToString();
  20. }
  21. catch (Exception ex)
  22. {
  23. return "";
  24. }
  25. }
  26.  
  27. /// <summary>
  28. ///将指定的Excel的文件转换成DataTable (Excel的第一个sheet)
  29. /// </summary>
  30. /// <param name="fullFielPath">文件的绝对路径</param>
  31. /// <returns></returns>
  32. public DataTable WorksheetToTable(string filePath)
  33. {
  34. try
  35. {
  36. FileInfo existingFile = new FileInfo(filePath);
  37.  
  38. ExcelPackage package = new ExcelPackage(existingFile);
  39. ExcelWorksheet worksheet = package.Workbook.Worksheets[];//选定 指定页
  40.  
  41. return WorksheetToTable(worksheet);
  42. }
  43. catch (Exception)
  44. {
  45. throw;
  46. }
  47. }
  48.  
  49. /// <summary>
  50. /// 将worksheet转成datatable
  51. /// </summary>
  52. /// <param name="worksheet">待处理的worksheet</param>
  53. /// <returns>返回处理后的datatable</returns>
  54. public static DataTable WorksheetToTable(ExcelWorksheet worksheet)
  55. {
  56. //获取worksheet的行数
  57. int rows = worksheet.Dimension.End.Row;
  58. //获取worksheet的列数
  59. int cols = worksheet.Dimension.End.Column;
  60.  
  61. DataTable dt = new DataTable(worksheet.Name);
  62. DataRow dr = null;
  63. for (int i = ; i <= rows; i++)
  64. {
  65. if (i > )
  66. dr = dt.Rows.Add();
  67.  
  68. for (int j = ; j <= cols; j++)
  69. {
  70. //默认将第一行设置为datatable的标题
  71. if (i == )
  72. dt.Columns.Add(GetString(worksheet.Cells[i, j].Value));
  73. //剩下的写入datatable
  74. else
  75. dr[j - ] = GetString(worksheet.Cells[i, j].Value);
  76. }
  77. }
  78. return dt;
  79. }
  80. }
  81. }

之前我有一个程序用的是方法一进行Excel导入的,速度不是很快,后来我又用了第二种方法但是速度更慢了,到底这两种方法哪种快,请大虾指导,还是我用第二种方法的时候业务判断有问题,不得而知,

就请明白人指导我到底这两种方法哪种比较好些;

3:实体类与DataTable之间的互转:

  1. /// <summary>
  2. /// DataTable与实体类互相转换
  3. /// </summary>
  4. /// <typeparam name="T">实体类</typeparam>
  5. public class ModelHandler<T> where T : new()
  6. {
  7. #region DataTable转换成实体类
  8.  
  9. /// <summary>
  10. /// 填充对象列表:用DataSet的第一个表填充实体类
  11. /// </summary>
  12. /// <param name="ds">DataSet</param>
  13. /// <returns></returns>
  14. public List<T> FillModel(DataSet ds)
  15. {
  16. if (ds == null || ds.Tables[] == null || ds.Tables[].Rows.Count == )
  17. {
  18. return null;
  19. }
  20. else
  21. {
  22. return FillModel(ds.Tables[]);
  23. }
  24. }
  25.  
  26. /// <summary>
  27. /// 填充对象列表:用DataSet的第index个表填充实体类
  28. /// </summary>
  29. public List<T> FillModel(DataSet ds, int index)
  30. {
  31. if (ds == null || ds.Tables.Count <= index || ds.Tables[index].Rows.Count == )
  32. {
  33. return null;
  34. }
  35. else
  36. {
  37. return FillModel(ds.Tables[index]);
  38. }
  39. }
  40.  
  41. /// <summary>
  42. /// 填充对象列表:用DataTable填充实体类
  43. /// </summary>
  44. public List<T> FillModel(DataTable dt)
  45. {
  46. if (dt == null || dt.Rows.Count == )
  47. {
  48. return null;
  49. }
  50. List<T> modelList = new List<T>();
  51. foreach (DataRow dr in dt.Rows)
  52. {
  53. //T model = (T)Activator.CreateInstance(typeof(T));
  54. T model = new T();
  55. for (int i = ; i < dr.Table.Columns.Count; i++)
  56. {
  57. PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
  58. if (propertyInfo != null && dr[i] != DBNull.Value)
  59. propertyInfo.SetValue(model, dr[i], null);
  60. }
  61.  
  62. modelList.Add(model);
  63. }
  64. return modelList;
  65. }
  66.  
  67. /// <summary>
  68. /// 填充对象:用DataRow填充实体类
  69. /// </summary>
  70. public T FillModel(DataRow dr)
  71. {
  72. if (dr == null)
  73. {
  74. return default(T);
  75. }
  76.  
  77. //T model = (T)Activator.CreateInstance(typeof(T));
  78. T model = new T();
  79.  
  80. for (int i = ; i < dr.Table.Columns.Count; i++)
  81. {
  82. PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
  83. if (propertyInfo != null && dr[i] != DBNull.Value)
  84. propertyInfo.SetValue(model,dr[i],null);
  85. }
  86. return model;
  87. }
  88.  
  89. #endregion
  90.  
  91. #region 实体类转换成DataTable
  92.  
  93. /// <summary>
  94. /// 实体类转换成DataSet
  95. /// </summary>
  96. /// <param name="modelList">实体类列表</param>
  97. /// <returns></returns>
  98. public DataSet FillDataSet(List<T> modelList)
  99. {
  100. if (modelList == null || modelList.Count == )
  101. {
  102. return null;
  103. }
  104. else
  105. {
  106. DataSet ds = new DataSet();
  107. ds.Tables.Add(FillDataTable(modelList));
  108. return ds;
  109. }
  110. }
  111.  
  112. /// <summary>
  113. /// 实体类转换成DataTable
  114. /// </summary>
  115. /// <param name="modelList">实体类列表</param>
  116. /// <returns></returns>
  117. public DataTable FillDataTable(List<T> modelList)
  118. {
  119. if (modelList == null || modelList.Count == )
  120. {
  121. return null;
  122. }
  123. DataTable dt = CreateData(modelList[]);
  124.  
  125. foreach(T model in modelList)
  126. {
  127. DataRow dataRow = dt.NewRow();
  128. foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
  129. {
  130. dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null);
  131. }
  132. dt.Rows.Add(dataRow);
  133. }
  134. return dt;
  135. }
  136.  
  137. /// <summary>
  138. /// 根据实体类得到表结构
  139. /// </summary>
  140. /// <param name="model">实体类</param>
  141. /// <returns></returns>
  142. private DataTable CreateData(T model)
  143. {
  144. DataTable dataTable = new DataTable(typeof (T).Name);
  145. foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
  146. {
  147. dataTable.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType));
  148. }
  149. return dataTable;
  150. }
  151.  
  152. #endregion
  153. }

3.1:将实体类转化成DataTable之后对DataTable进行操作

  1.  
  1. //首先将数据库中查出的数据变成实体类集合,然后将实体类集合转变成DataTable表格
  2. //dataPercent,然后在对此表格进行操作,表头转化和表格信息
    //设置新表的表头:即字段名,有英文改为中文
    1 for (int i = ; i < dataPercent.Columns.Count; i++)
  3. {
  4. DataColumn column = dataPercent.Columns[i];
  5. string name = column.ColumnName;
  6. switch (name)
  7. {
  8. case "IsDomestic":
  9. dataPercent.Columns[i].ColumnName = "国内/国际";
  10. break;
  11. case "TripType":
  12. dataPercent.Columns[i].ColumnName = "行程类型";
  13. break;
  14. case "GoFlightCode":
  15. dataPercent.Columns[i].ColumnName = "去程航班号";
  16. break;
  17. case "GoCabin":
  18. dataPercent.Columns[i].ColumnName = "去程舱位";
  19. break;
  20. case "GoSeatNum":
  21. dataPercent.Columns[i].ColumnName = "去程座位数";
  22. break;
  23. case "Line":
  24. dataPercent.Columns[i].ColumnName = "去程行程";
  25. break;
  26. case "DepartDate":
  27. dataPercent.Columns[i].ColumnName = "去程航班日期";
  28. break;
  29. case "BackFlightCode":
  30. dataPercent.Columns[i].ColumnName = "回程航班号";
  31. break;
  32. case "BackCabin":
  33. dataPercent.Columns[i].ColumnName = "回程舱位";
  34. break;
  35. case "ReturnDate":
  36. dataPercent.Columns[i].ColumnName = "回程航班日期";
  37. break;
  38. case "BackSeatNum":
  39. dataPercent.Columns[i].ColumnName = "回程座位数";
  40. break;
  41. case "AvCmd":
  42. dataPercent.Columns[i].ColumnName = "黑屏的AV查询指令";
  43. break;
  44. case "State":
  45. dataPercent.Columns[i].ColumnName = "状态";
  46. break;
  47. case "Interval":
  48. dataPercent.Columns[i].ColumnName = "间隔时间(分钟)";
  49. break;
  50. case "Telphone":
  51. dataPercent.Columns[i].ColumnName = "联系电话";
  52. break;
  53. case "Remark":
  54. dataPercent.Columns[i].ColumnName = "备注";
  55. break;
  56. }
  57. }
  58. DataTable dtResult = new DataTable();
  59. //克隆表结构
  60. dtResult = dataPercent.Clone();
               //将克隆的表格进行字段类型的重置,有利于改变表格数据
  61. foreach (DataColumn col in dtResult.Columns)
  62. {
  63. if (col.ColumnName == "行程类型" || col.ColumnName == "国内/国际" ||col.ColumnName =="状态")
  64. {
  65. //修改列类型
  66. col.DataType = typeof(String);
  67. }
  68. }
  69. foreach (DataRow row in dataPercent.Rows)
  70. {
  71. DataRow rowNew = dtResult.NewRow();
  72. //rowNew["Id"] = row["Id"];
  73. rowNew["国内/国际"] = row["国内/国际"] == "true" ? "是" : "否";
  74. rowNew["行程类型"] = row["行程类型"] == "" ? "单程" : "往返";
  75. rowNew["去程航班号"] = row["去程航班号"];
  76. rowNew["去程舱位"] = row["去程舱位"];
  77. rowNew["去程座位数"] = row["去程座位数"];
  78. rowNew["去程行程"] = row["去程行程"];
  79. rowNew["去程航班日期"] = row["去程航班日期"];
  80. rowNew["回程航班号"] = row["回程航班号"];
  81. rowNew["回程舱位"] = row["回程舱位"];
  82. rowNew["回程航班日期"] = row["回程航班日期"];
  83. rowNew["回程座位数"] = row["回程座位数"];
  84. rowNew["黑屏的AV查询指令"] = row["黑屏的AV查询指令"];
  85. //rowNew["创建人Id"] = row["创建人Id"];
  86. rowNew["状态"] = row["状态"] == "" ? "有效" : "挂起";
  87. rowNew["间隔时间(分钟)"] = row["间隔时间(分钟)"];
  88. rowNew["联系电话"] = row["联系电话"];
  89. rowNew["备注"] = row["备注"];
  90. dtResult.Rows.Add(rowNew);
  91. }

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. Windows系统前端常用PS快捷键:

    1.设置滚轮放大缩小: 编辑--首选项--常规--用滚轮缩放 2.V 移动 ctrl+v 自动选中(图层), 3.M 选框 Shift+M 变换形状 Alt :确定圆形/矩形中心 Shift: 圆形/ ...

  2. [转] DDD领域驱动设计(三) 之 理论知识收集汇总

    最近一直在学习领域驱动设计(DDD)的理论知识,从网上搜集了一些个人认为比较有价值的东西,贴出来和大家分享一下: 我一直觉得不要盲目相信权威,比如不能一谈起领域驱动设计,就一定认为国外的那个Eric ...

  3. SpringMVC中使用Swagger2整合

    Swagger2是什么 Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件. Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 W ...

  4. JSON总结-持续更新补充

    基本的json格式 { "name": "jobs", "boolean": true, "age": null, &q ...

  5. dubbo 请求调用过程分析

    服务消费方发起请求 当服务的消费方引用了某远程服务,服务的应用方在spring的配置实例如下: <dubbo:referenceid="demoService"interfa ...

  6. Vim按Esc后光标左移问题的解决

    参考了这篇文章http://vim.wikia.com/wiki/Prevent_escape_from_moving_the_cursor_one_character_to_the_left 在Vi ...

  7. js代码风格之链式结构

    <div class="box"> <ul class="menu"> <li class="level1"& ...

  8. Chrome DevTools 调研笔记

    1  说明 此篇文章针对Chrome DevTools常用功能进行调研分析.描述了每个功能点能实现的功能.应用场景和详细操作. 2  Elements 2.1  功能 检查和实时更新页面的HTML与C ...

  9. 一个非常简单的例子告诉你attachEvent和addEventListener的区别

    <input id="test" type="button" value="测试"> <script> var te ...

  10. javaWeb第一天

    //第一个JavaWeb项目package com.chy.action; import java.io.IOException; import javax.servlet.ServletExcept ...