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可以操作 ...
随机推荐
- 实例讲解如何利用jQuery设置图片居中放大或者缩小
大家有没有见过其他网站的图片只要鼠标放上去就能放大,移出去的时候就能缩小,而且一直保持居中显示!其实jQuery提供一个animate函数可以使图片放大和缩小,只要改变图片的长和高就OK啦!但是ani ...
- c++ tie,ignore
ignore 一个未指定的类型对象,任何值都可以没有影响地赋值给它.通常使用tie来解压一个元组,作为可以忽略的占位符. #include <iostream> #include < ...
- [WorldFinal 2012E]Infiltration(dfs+图论)
Description 题意:给定一个点数为n的竞赛图,求图的最小支配集 n<=75 Solution 如果将竞赛图的一个点删去,这个图还是竞赛图 而竞赛图每个点相连的边数为(n-1),那么删去 ...
- gcc常用命令
1简介 2简单编译 2.1预处理 2.2编译为汇编代码(Compilation) 2.3汇编(Assembly) 2.4连接(Linking) 3多个程序文件的编译 4检错 5库文件连接 5.1编译成 ...
- TouTiao开源项目 分析笔记14 段子评论
1.段子页面详情 1.1.先看看预览界面吧 左边的页面已经实现了,现在的目的就是要实现点击左侧的每一个item 然后跳转到右边相应的段子详情页面. 1.2.首先肯定有右侧这个活动==>JokeC ...
- C#中接口与抽象类的区别
接口与抽象类是面试中经常会考到的点,容易混淆.首先了解下两者的概念: 一.抽象类: 抽象类是特殊的类,只是不能被实例化:除此以外,具有类的其他特性:重要的是抽象类可以包括抽象方法,这是普通类 ...
- lnmp一键安装环境中nginx开启pathinfo
问题及原理可参考:http://www.laruence.com/2009/11/13/1138.html 如果是用lnmp脚本一键安装的开发环境,可以通过如下方式开户pathinfo: 1.注释ng ...
- PEAR DB 事务相关
1.autoCommit().commit().rollback() function autoCommit($onoff=false) 指定是否自动提交事务.有的后端数据库不支持. function ...
- Linux开启MySQL远程连接
Linux开启MySQL远程连接的设置步骤 . MySQL默认root用户只能本地访问,不能远程连接管理MySQL数据库,那么Linux下如何开启MySQL远程连接?设置步骤如下: 1.GRANT命令 ...
- CodeForces Round #515 Div.3 D. Boxes Packing
http://codeforces.com/contest/1066/problem/D Maksim has nn objects and mm boxes, each box has size e ...