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可以操作 ...
随机推荐
- 数据分析处理库Pandas——merge操作
有一列列名相同值也相同 有两列列名相同值也相同 按其中一列合并 按两列合并 有一列列名相同值也相同,有一列列名相同值不相同,按两列合并 列名相同值不相同的行删掉 保留所有行 保留所有行并显示合并后该值 ...
- python爬虫:利用正则表达式爬取豆瓣读书首页的book
1.问题描述: 爬取豆瓣读书首页的图书的名称.链接.作者.出版日期,并将爬取的数据存储到Excel表格Douban_I.xlsx中 2.思路分析: 发送请求--获取数据--解析数据--存储数据 1.目 ...
- JS简写
本文来源于多年的 JavaScript 编码技术经验,适合所有正在使用 JavaScript 编程的开发人员阅读. 本文的目的在于帮助大家更加熟练的运用 JavaScript 语言来进行开发工作. 文 ...
- 工作中遇到的比较奇怪的一些sql(一些子查询)
在列中进行子查询 1.在一个表中有多个员工ID,比如一个下单员工,一个修改订单的员工,可以使用在列中进行子查询,具体如下: ( SELECT staff_name FROM sp_staff_basi ...
- Partitioning by Palindromes UVA - 11584 简单dp
题目:题目链接 思路:预处理出l到r为回文串的子串,然后如果j到i为回文串,dp[i] = min(dp[i], dp[j] + 1) AC代码: #include <iostream> ...
- POJ:2385-Apple Catching(dp经典题)
Apple Catching Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 14311 Accepted: 7000 Descr ...
- ABAP News for Release 7.51 – ABAP CDS Client Handling
Open SQLは自動的クライアント処理をサポートしています. Open SQLでクライアント依存のデータソースにアクセスする時.デフォルトでは現在のクライアントのデータだけが考慮されます. クライア ...
- saltstack执行远程命令
目录 Remote Execution salt state salt state 系统 salt state 系统流程 Runner salt runner Orchestrate Runner S ...
- 5,pandas高级数据处理
1.删除重复元素 使用duplicated()函数检测重复的行,返回元素为布尔类型的Series对象,每个元素对应一行,如果该行不是第一次出现,则元素为True - keep参数:指定保留哪一重复的行 ...
- [bzoj3071]N皇后
哈哈哈水题~ 但是不能一眼看出来的..我想了一个小时?! 题面 Description “国际象棋中,一方的皇后数不能超过5个” 一个N*N的棋盘,任意摆放皇后,最坏情况下最少需要多少个皇后才能保证所 ...