EPPlusHelper
public class EPPlusExcelHelper : IDisposable
{
public ExcelPackage ExcelPackage { get; private set; }
private Stream fs; public EPPlusExcelHelper(string filePath)
{
if (File.Exists(filePath))
{
var file = new FileInfo(filePath);
ExcelPackage = new ExcelPackage(file);
}
else
{
fs = File.Create(filePath);
ExcelPackage = new ExcelPackage(fs); }
}
/// <summary>
/// 获取sheet,没有时创建
/// </summary>
/// <param name="sheetName"></param>
/// <returns></returns>
public ExcelWorksheet GetOrAddSheet(string sheetName)
{
ExcelWorksheet ws = ExcelPackage.Workbook.Worksheets.FirstOrDefault(i => i.Name == sheetName);
if (ws == null)
{
ws = ExcelPackage.Workbook.Worksheets.Add(sheetName);
}
return ws;
}
/// <summary>
/// 使用EPPlus导出Excel(xlsx)
/// </summary>
/// <param name="ExcelPackage">ExcelPackage</param>
/// <param name="sourceTable">数据源</param>
public void AppendSheetToWorkBook(DataTable sourceTable)
{
AppendSheetToWorkBook(sourceTable, true);
}
/// <summary>
/// 使用EPPlus导出Excel(xlsx)
/// </summary>
/// <param name="ExcelPackage">ExcelPackage</param>
/// <param name="sourceTable">数据源</param>
/// <param name="isDeleteSameNameSheet">是否删除同名的sheet</param>
public void AppendSheetToWorkBook(DataTable sourceTable, bool isDeleteSameNameSheet)
{
//Create the worksheet ExcelWorksheet ws = AddSheet(sourceTable.TableName, isDeleteSameNameSheet); //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
ws.Cells["A1"].LoadFromDataTable(sourceTable, true); //Format the row
FromatRow(sourceTable.Rows.Count, sourceTable.Columns.Count, ws); } /// <summary>
/// 删除指定的sheet
/// </summary>
/// <param name="ExcelPackage"></param>
/// <param name="sheetName"></param>
public void DeleteSheet(string sheetName)
{
var sheet = ExcelPackage.Workbook.Worksheets.FirstOrDefault(i => i.Name == sheetName);
if (sheet != null)
{
ExcelPackage.Workbook.Worksheets.Delete(sheet);
}
}
/// <summary>
/// 导出列表到excel,已存在同名sheet将删除已存在的
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="ExcelPackage"></param>
/// <param name="list">数据源</param>
/// <param name="sheetName">sheet名称</param>
public void AppendSheetToWorkBook<T>(IEnumerable<T> list, string sheetName)
{
AppendSheetToWorkBook(list, sheetName, true);
}
/// <summary>
/// 导出列表到excel,已存在同名sheet将删除已存在的
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="ExcelPackage"></param>
/// <param name="list">数据源</param>
/// <param name="sheetName">sheet名称</param>
/// <param name="isDeleteSameNameSheet">是否删除已存在的同名sheet,false时将重命名导出的sheet</param>
public void AppendSheetToWorkBook<T>(IEnumerable<T> list, string sheetName, bool isDeleteSameNameSheet)
{
ExcelWorksheet ws = AddSheet(sheetName, isDeleteSameNameSheet); //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
ws.Cells["A1"].LoadFromCollection(list, true); } /// <summary>
/// 添加文字图片
/// </summary>
/// <param name="sheet"></param>
/// <param name="msg">要转换成图片的文字</param>
public void AddPicture(string sheetName, string msg)
{
Bitmap img = GetPictureString(msg); var sheet = GetOrAddSheet(sheetName);
var picName = "92FF5CFE-2C1D-4A6B-92C6-661BDB9ED016";
var pic = sheet.Drawings.FirstOrDefault(i => i.Name == picName);
if (pic != null)
{
sheet.Drawings.Remove(pic);
}
pic = sheet.Drawings.AddPicture(picName, img); pic.SetPosition(, , , );
}
/// <summary>
/// 文字绘制图片
/// </summary>
/// <param name="msg"></param>
/// <returns></returns>
private static Bitmap GetPictureString(string msg)
{
var msgs = msg.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
var maxLenght = msgs.Max(i => i.Length);
var rowCount = msgs.Count();
var rowHeight = ;
var fontWidth = ;
var img = new Bitmap(maxLenght * fontWidth, rowCount * rowHeight);
using (Graphics g = Graphics.FromImage(img))
{
g.Clear(Color.White);
Font font = new Font("Arial", , (FontStyle.Bold));
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(, , img.Width, img.Height), Color.Blue, Color.DarkRed, 1.2f, true); for (int i = ; i < msgs.Count(); i++)
{
g.DrawString(msgs[i], font, brush, , + rowHeight * i);
}
} return img;
} /// <summary>
/// List转DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <returns></returns>
public DataTable ListToDataTable<T>(IEnumerable<T> data)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable dataTable = new DataTable();
for (int i = ; i < properties.Count; i++)
{
PropertyDescriptor property = properties[i];
dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
}
object[] values = new object[properties.Count];
foreach (T item in data)
{
for (int i = ; i < values.Length; i++)
{
values[i] = properties[i].GetValue(item);
} dataTable.Rows.Add(values);
}
return dataTable;
}
/// <summary>
/// 插入行
/// </summary>
/// <param name="sheet"></param>
/// <param name="values">行类容,一个单元格一个对象</param>
/// <param name="rowIndex">插入位置,起始位置为1</param>
public void InsertValues(string sheetName, List<object> values, int rowIndex)
{
var sheet = GetOrAddSheet(sheetName);
sheet.InsertRow(rowIndex, );
int i = ;
foreach (var item in values)
{
sheet.SetValue(rowIndex, i, item);
i++;
}
} /// <summary>
/// 保存修改
/// </summary>
public void Save()
{
ExcelPackage.Save();
} /// <summary>
/// 添加Sheet到ExcelPackage
/// </summary>
/// <param name="ExcelPackage">ExcelPackage</param>
/// <param name="sheetName">sheet名称</param>
/// <param name="isDeleteSameNameSheet">如果存在同名的sheet是否删除</param>
/// <returns></returns>
private ExcelWorksheet AddSheet(string sheetName, bool isDeleteSameNameSheet)
{
if (isDeleteSameNameSheet)
{
DeleteSheet(sheetName);
}
else
{
while (ExcelPackage.Workbook.Worksheets.Any(i => i.Name == sheetName))
{
sheetName = sheetName + "(1)";
}
} ExcelWorksheet ws = ExcelPackage.Workbook.Worksheets.Add(sheetName);
return ws;
} private void FromatRow(int rowCount, int colCount, ExcelWorksheet ws)
{
ExcelBorderStyle borderStyle = ExcelBorderStyle.Thin;
Color borderColor = Color.FromArgb(, , ); using (ExcelRange rng = ws.Cells[, , rowCount + , colCount])
{
rng.Style.Font.Name = "宋体";
rng.Style.Font.Size = ;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(, , )); rng.Style.Border.Top.Style = borderStyle;
rng.Style.Border.Top.Color.SetColor(borderColor); rng.Style.Border.Bottom.Style = borderStyle;
rng.Style.Border.Bottom.Color.SetColor(borderColor); rng.Style.Border.Right.Style = borderStyle;
rng.Style.Border.Right.Color.SetColor(borderColor);
} //Format the header row
using (ExcelRange rng = ws.Cells[, , , colCount])
{
rng.Style.Font.Bold = true;
rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(, , )); //Set color to dark blue
rng.Style.Font.Color.SetColor(Color.FromArgb(, , ));
}
} public void Dispose()
{
ExcelPackage.Dispose();
if (fs != null)
{
fs.Dispose();
fs.Close();
} }
}
EPPlusHelper的更多相关文章
- ASP.NET Core使用EPPlus操作Excel
1.前言 本篇文章通过ASP.NET Core的EPPlus包去操作Excel(导入导出),其使用原理与NPOI类似,导出Excel的时候不需要电脑上安装office,非常好用 2.使用 新建一个AS ...
- C# 使用Epplus导出Excel [4]:合并指定行
C# 使用Epplus导出Excel [1]:导出固定列数据 C# 使用Epplus导出Excel [2]:导出动态列数据 C# 使用Epplus导出Excel [3]:合并列连续相同数据 C# 使用 ...
- C# 使用Epplus导出Excel [3]:合并列连续相同数据
C# 使用Epplus导出Excel [1]:导出固定列数据 C# 使用Epplus导出Excel [2]:导出动态列数据 C# 使用Epplus导出Excel [3]:合并列连续相同数据 C# 使用 ...
- C# 使用Epplus导出Excel [2]:导出动态列数据
C# 使用Epplus导出Excel [1]:导出固定列数据 C# 使用Epplus导出Excel [2]:导出动态列数据 C# 使用Epplus导出Excel [3]:合并列连续相同数据 C# 使用 ...
- C# 使用Epplus导出Excel [1]:导出固定列数据
C# 使用Epplus导出Excel [1]:导出固定列数据 C# 使用Epplus导出Excel [2]:导出动态列数据 C# 使用Epplus导出Excel [3]:合并列连续相同数据 C# 使用 ...
- ExcelUtility 对excel的序列化与反序列化,支持当单元格中数据为空时将属性赋值为指定类型的默认值
源码https://github.com/leoparddne/EPPlusHelper 安装: Install-Package ExcelUtility -Version 1.1.4 需要为对象添加 ...
- .net mvc中epplus导出excel
帮助类 using OfficeOpenXml; using OfficeOpenXml.Style; using System; using System.Collections.Generic; ...
随机推荐
- 分析python日志重复输出问题
问题起源: 在学习了python的函数式编程后,又接触到了logging这样一个强大的日志模块.为了减少重复代码,应该不少同学和我一样便迫不及待的写了一个自己的日志函数,比如下面这样: impor ...
- 【ES6】Generator+Promise异步编程
一.概念 首先我们要理解Generator和Promise的概念. Generator:意思是生成器,可以在函数内部通过yeild来控制语句的执行或暂停状态. *Foo(){ yeild consol ...
- VS 中 无法嵌入互操作类型“……”,请改用适用的接口的解决方法
在引用COM组件的时候,出现了无法嵌入互操作类型"--",请改用适用的接口的错误提示. 选中项目中引入的dll,鼠标右键,选择属性,把"嵌入互操作类型"设置为F ...
- .net core 摸索之路
1:先安装vs core 下载地址:http://cdn7.mydown.com/5cc50443/fbaddadae50d260bcac7401e87e9e2c9/newsoft/VSCode_ ...
- oracle主键和索引
主键:能够唯一标识一条记录的字段为主键(亦或主码),不能重复的,不允许为空.作用:用来保证数据完整性个数:主键只能有一个 索引:作用:是提高查询排序的速度个数:一个表可以有多个索引 常用索引类型:No ...
- 纯javascript实现可拖住/大小的div
好久没写了,不得不说人懒了好多.. 也不打算实现什么太厉害的功能,因为不喜欢网上那些一大堆代码的,看的头晕,于是自己写了一个 旨在越简单越好(当然也走点形式- -其实是自己菜),所以一些宽度和高度都写 ...
- tyflow雨滴在物体上滑落测试
http://docs.tyflow.com/download/
- 圆形进度条css3样式
<view class="con"> <view class="percent-circle percent-circle-left"> ...
- pyqt5之简单窗口的创建
在学完tkinter后,发现tkinter在布局方面特别的不方便(Tkinter资料:http://effbot.org/tkinterbook/tkinter-index.htm),因此学习pyqt ...
- Python函数式编程之装饰器
原则:对修改是封闭的,对扩展是开放的,方法:一般不修改函数或者类,而是扩展函数或者类 一:装饰器 允许我们将一个提供核心功能的对象和其他可以改变这个功能的对象’包裹‘在一起, 使用装饰对象的任何对象与 ...