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);
}
上一篇:电脑变WIFI:建立虚拟共享WIFI热点可查看WIFI密码windows中使用bat批处理命令提示符cmd创建教程含工具


下一篇:Spring Cloud和Docker搭建微服务平台