C# 操作Excel,使用EPPlus
EPPlus下载地址:http://www.codeplex.com/EPPlus
引用命名空间:
using OfficeOpenXml;
using OfficeOpenXml.Table;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Reflection;
using System.Web; public static class ExcelUtil
{
private static void dataTableToCsv(DataTable table, string file)
{
string title = "";
FileStream fs = new FileStream(file, FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default); for (int i = ; i < table.Columns.Count; i++)
{
title += table.Columns[i].ColumnName + "\t"; //栏位:自动跳到下一单元格
} title = title.Substring(, title.Length - ) + "\n";
sw.Write(title); foreach (DataRow row in table.Rows)
{
string line = ""; for (int i = ; i < table.Columns.Count; i++)
{
line += row[i].ToString().Trim() + "\t"; //内容:自动跳到下一单元格
}
line = line.Substring(, line.Length - ) + "\n";
sw.Write(line);
}
sw.Close();
fs.Close();
} /// <summary>
/// 将一组对象导出成EXCEL
/// </summary>
/// <typeparam name="T">要导出对象的类型</typeparam>
/// <param name="objList">一组对象</param>
/// <param name="FileName">导出后的文件名</param>
/// <param name="columnInfo">列名信息</param>
public static void ExExcel<T>(List<T> objList, string FileName, Dictionary<string, string> columnInfo)
{
ExExcel(objList, FileName, columnInfo, null);
} /// <summary>
/// 将一组对象导出成EXCEL
/// </summary>
/// <typeparam name="T">要导出对象的类型</typeparam>
/// <param name="objList">一组对象</param>
/// <param name="FileName">导出后的文件名</param>
/// <param name="columnInfo">列名信息</param>
/// <param name="other">追加其他内容</param>
public static void ExExcel<T>(List<T> objList, string FileName, Dictionary<string, string> columnInfo, string other)
{
if (columnInfo.Count == ) { return; }
if (objList.Count == ) { return; }
//生成EXCEL的HTML
string excelStr = ""; Type myType = objList[].GetType();
//根据反射从传递进来的属性名信息得到要显示的属性
List<PropertyInfo> myPro = new List<PropertyInfo>();
foreach (string cName in columnInfo.Keys)
{
PropertyInfo p = myType.GetProperty(cName);
if (p != null)
{
myPro.Add(p);
excelStr += columnInfo[cName] + "\t";
}
}
//如果没有找到可用的属性则结束
if (myPro.Count == ) { return; }
excelStr += "\n"; foreach (T obj in objList)
{
foreach (PropertyInfo p in myPro)
{
excelStr += p.GetValue(obj, null) + "\t";
}
excelStr += "\n";
}
if (!string.IsNullOrEmpty(other))
{
excelStr += other;
}
//输出EXCEL
HttpResponse rs = System.Web.HttpContext.Current.Response;
rs.Clear();
rs.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
rs.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, Encoding.UTF8));
rs.ContentType = "application/ms-excel";
rs.Write(excelStr);
rs.End();
} #region 保存数据列表到Excel(泛型)+void SaveToExcel<T>(IEnumerable<T> data, string FileName, string OpenPassword = "")
/// <summary>
/// 保存数据列表到Excel(泛型)
/// </summary>
/// <typeparam name="T">集合数据类型</typeparam>
/// <param name="data">数据列表</param>
/// <param name="FileName">Excel文件</param>
/// <param name="OpenPassword">Excel打开密码</param>
public static void SaveToExcel<T>(IEnumerable<T> data, string FileName, string OpenPassword = "")
{
FileInfo file = new FileInfo(FileName);
try
{
using (ExcelPackage ep = new ExcelPackage(file, OpenPassword))
{
ExcelWorksheet ws = ep.Workbook.Worksheets.Add(typeof(T).Name);
ws.Cells["A1"].LoadFromCollection(data, true, TableStyles.Medium10); ep.Save(OpenPassword);
}
}
catch (InvalidOperationException ex)
{
//Console.WriteLine(ex.Message);
throw ex;
}
}
#endregion #region 从Excel中加载数据(泛型)+IEnumerable<T> LoadFromExcel<T>(string FileName) where T : new()
/// <summary>
/// 从Excel中加载数据(泛型)
/// </summary>
/// <typeparam name="T">每行数据的类型</typeparam>
/// <param name="FileName">Excel文件名</param>
/// <returns>泛型列表</returns>
private static IEnumerable<T> LoadFromExcel<T>(string FileName) where T : new()
{
FileInfo existingFile = new FileInfo(FileName);
List<T> resultList = new List<T>();
Dictionary<string, int> dictHeader = new Dictionary<string, int>(); using (ExcelPackage package = new ExcelPackage(existingFile))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[]; int colStart = worksheet.Dimension.Start.Column; //工作区开始列
int colEnd = worksheet.Dimension.End.Column; //工作区结束列
int rowStart = worksheet.Dimension.Start.Row; //工作区开始行号
int rowEnd = worksheet.Dimension.End.Row; //工作区结束行号 //将每列标题添加到字典中
for (int i = colStart; i <= colEnd; i++)
{
dictHeader[worksheet.Cells[rowStart, i].Value.ToString()] = i;
} List<PropertyInfo> propertyInfoList = new List<PropertyInfo>(typeof(T).GetProperties()); for (int row = rowStart + ; row < rowEnd; row++)
{
T result = new T(); //为对象T的各属性赋值
foreach (PropertyInfo p in propertyInfoList)
{
try
{
ExcelRange cell = worksheet.Cells[row, dictHeader[p.Name]]; //与属性名对应的单元格 if (cell.Value == null)
continue;
switch (p.PropertyType.Name.ToLower())
{
case "string":
p.SetValue(result, cell.GetValue<String>(), null);
break;
case "int16":
p.SetValue(result, cell.GetValue<Int16>(), null);
break;
case "int32":
p.SetValue(result, cell.GetValue<Int32>(), null);
break;
case "int64":
p.SetValue(result, cell.GetValue<Int64>(), null);
break;
case "decimal":
p.SetValue(result, cell.GetValue<Decimal>(), null);
break;
case "double":
p.SetValue(result, cell.GetValue<Double>(), null);
break;
case "datetime":
p.SetValue(result, cell.GetValue<DateTime>(), null);
break;
case "boolean":
p.SetValue(result, cell.GetValue<Boolean>(), null);
break;
case "byte":
p.SetValue(result, cell.GetValue<Byte>(), null);
break;
case "char":
p.SetValue(result, cell.GetValue<Char>(), null);
break;
case "single":
p.SetValue(result, cell.GetValue<Single>(), null);
break;
default:
break;
}
}
catch (KeyNotFoundException ex)
{
throw ex;
}
}
resultList.Add(result);
}
}
return resultList;
}
#endregion /// <summary>
/// 创造参数对
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="comnName"></param>
/// <param name="func"></param>
/// <returns></returns>
public static KeyValuePair<string, Func<T, string>> CreateKVP<T>(string comnName, Func<T, string> func)
{
return new KeyValuePair<string, Func<T, string>>(comnName, func);
} /// <summary>
/// 向表中添加列
/// </summary>
/// <param name="sheet"></param>
/// <param name="columnName"></param>
public static void AddSheetHeadRange(this ExcelWorksheet sheet, params string[] columnNames)
{
for (int i = ; i < columnNames.Length; i++)
sheet.Cells[, i + ].Value = columnNames[i];
} /// <summary>
/// 向表中添加行数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sheet"></param>
/// <param name="listSources"></param>
/// <param name="values"></param>
public static void AddSheetRow<T>(this ExcelWorksheet sheet, IList<T> listSources, params KeyValuePair<string, Func<T, string>>[] values)
{
if (values != null && values.Length > )
{
sheet.AddSheetHeadRange(values.Select(item => item.Key).ToArray());
if (listSources != null && listSources.Count > )
{
IList<Func<T, string>> listVs = values.Select(item => item.Value).ToList();
for (int i = ; i < listSources.Count; i++)
{
for (int j = ; j < listVs.Count; j++)
{
sheet.Cells[(i + ), (j + )].Value = listVs[j](listSources[i]);
}
}
}
}
}
}
ExcelUtil
使用如下:
System.IO.MemoryStream output = new System.IO.MemoryStream();
using (ExcelPackage package = new ExcelPackage(output))
{
ExcelWorksheet sheet = package.Workbook.Worksheets.Add("Demo");
sheet.AddSheetRow<TEntity>(new List<TEntity>(),
ExcelUtil.CreateKVP<TEntity>("col1", item => item.P1),
ExcelUtil.CreateKVP<TEntity>("col2", item => item.P2)
);
sheet.Cells.AutoFitColumns(0);
string filename =string.Format("/uploads/{0}.xls", DateTime.Now.ToString("yyyyMMdd"));
package.SaveAs(new System.IO.FileInfo(Server.MapPath(filename)));
output.Position = 0;
}
C# 操作Excel,使用EPPlus的更多相关文章
- 使用EPPLUS操作EXcel
使用EPPLUS操作EXcel 时间 2014-11-06 19:28:01 姜糖水 原文 http://www.cnphp6.com/archives/58648 主题 Excel 1 下载Ep ...
- ASP.NET Core使用EPPlus操作Excel
1.前言 本篇文章通过ASP.NET Core的EPPlus包去操作Excel(导入导出),其使用原理与NPOI类似,导出Excel的时候不需要电脑上安装office,非常好用 2.使用 新建一个AS ...
- C#使用第三方组件Epplus操作Excel表
Epplus操作Excel基础详解 1.什么是Epplus Epplus是一个使用Open Office XML文件格式,能读写Excel2007/2010文件的开源组件,在导出Excel的时候不需要 ...
- [Solution] NPOI操作Excel
NPOI 是 POI 项目的 .NET 版本.POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目.使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 ...
- .net 操作excel
.net 操作excel的常用组件:EPPlus,NPOI 1.NPOI,即POI的.NET版本(POI是一套用Java写成的库,能够帮助开发者在没有安装微软Office的情况下读写Office文件, ...
- C# 操作 Excel(.xls和.xlsx)文件
C#创建Excel(.xls和.xlsx)文件的三种方法 .NET 使用NPOI导入导出标准Excel C# 使用NPOI 实现Excel的简单导入导出 NET使用NPOI组件将数据导出Excel-通 ...
- [Asp.net] C# 操作Excel的几种方式 优缺点比较
在项目中我们常常需要将数据库中的数据导出成Excel文件 有一次工作中我的目的就是读取Excel到内存中,整理成指定格式 整理后再导出到Excel. 因为我要处理的每个Excel表格文件很大.一个表格 ...
- 免费高效实用的.NET操作Excel组件NPOI(.NET组件介绍之六)
很多的软件项目几乎都包含着对文档的操作,前面已经介绍过两款操作文档的组件,现在介绍一款文档操作的组件NPOI. NPOI可以生成没有安装在您的服务器上的Microsoft Office套件的Excel ...
- C#通过NPOI操作Excel
参考页面: http://www.yuanjiaocheng.net/webapi/create-crud-api-1-post.html http://www.yuanjiaocheng.net/w ...
- POI操作Excel
POI和Excel简介 JAVA中操作Excel的有两种比较主流的工具包: JXL 和 POI .jxl 只能操作Excel 95, 97, 2000也即以.xls为后缀的excel.而poi可以操作 ...
随机推荐
- swoole中swoole_timer_tick回调函数使用对象方法
swoole_timer_tick的回调函数无法使用类似于array($this, 'method')来调用对象方法,所以我用一下方法变通了一下来调用 swoole_timer_tick(1000, ...
- Bootstrap3适配IE8浏览器的方法
<!--[if lte IE 8]> <script src="js/respond.min.js"></script> <script ...
- 十、mysql之索引原理与慢查询优化
mysql之索引原理与慢查询优化 一.介绍 1.什么是索引? 一般的应用系统,读写比例在10:1左右,而且插入操作和一般的更新操作很少出现性能问题,在生产环境中,我们遇到最多的,也是最容易出问题的,还 ...
- Java集合——LinkedHashMap源码详解
个KV.LinkedHashMap不仅像HashMap那样对其进行基于哈希表和单链表的Entry数组+ next链表的存储方式,而且还结合了LinkedList的优点,为每个Entry节点增加了前驱和 ...
- 理解Queue队列中join()与task_done()的关系
在网上大多关于join()与task_done()的结束原话是这样的: Queue.task_done() 在完成一项工作之后,Queue.task_done()函数向任务已经完成的队列发送一个信号 ...
- 直接选择排序&堆排序
1.什么是直接选择排序? 直接选择排序(Straight Select Sort)是一种简单的排序方法,它的基本思想是:通过n-i次关键字之间的比较,从n-i+1个记录中选出关键字最小的记录,并和第i ...
- svn Previous operation has not finished; run 'cleanup' if it was interrupted
svn cleanup failed–previous operation has not finished; run cleanup if it was interrupted Usually, a ...
- The GNU C Library
Any Unix-like operating system needs a C library: the library which defines the ``system calls'' and ...
- DOS程序员手册(三)
56页 第4章DOS和BIOS接口 本章介绍了用户程序访问DOS内核和BIOS所提供的各种服务的方法.为了访问这 些服务,我们可以从任何编程语言中调用各个软件中断,这些中断便是我们在本 ...
- 【Training versus Testing】林轩田机器学习基石
接着上一讲留下的关子,机器学习是否可行与假设集合H的数量M的关系. 机器学习是否可行的两个关键点: 1. Ein(g)是否足够小(在训练集上的表现是否出色) 2. Eout(g)是否与Ein(g)足够 ...