C#EPPlus帮助类(EPPlusExcelHelper)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>
/// DataTable数据导出到Excel(xlsx)
/// </summary>
/// <param name="ExcelPackage">ExcelPackage</param>
/// <param name="sourceTable">数据源</param>
public void AppendSheetToWorkBook(DataTable sourceTable)
{
AppendSheetToWorkBook(sourceTable, true);
}
/// <summary>
/// DataTable数据导出到Excel(xlsx)
/// </summary>
/// <param name="ExcelPackage">ExcelPackage</param>
/
// <param name="sourceTable">数据源</param>
/// <param name="isDeleteSameNameSheet">是否删除同名的sheet</param>
public void AppendSheetToWorkBook(DataTable sourceTable, bool isDeleteSameNameSheet)
{
//创建worksheet
ExcelWorksheet ws = AddSheet(sourceTable.TableName, isDeleteSameNameSheet);
//从单元格A1开始,将数据表加载到⼯作表中。第1⾏输出列名
ws.Cells["A1"].LoadFromDataTable(sourceTable, true);
//格式化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);
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(3, 0, 6, 0);
}
/// <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 = 23;
var fontWidth = 17;
var img = new Bitmap(maxLenght * fontWidth, rowCount * rowHeight);
using (Graphics g = Graphics.FromImage(img))
{
g.Clear(Color.White);
Font font = new Font("Arial", 12, (FontStyle.Bold));
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, img.Width, img.Height), Color.Blue, Color.DarkRed, 1.2f, true);            for (int i = 0; i < msgs.Count(); i++)
{
g.DrawString(msgs[i], font, brush, 3, 2 + 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 = 0; 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 = 0; 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, 1);
int i = 1;
foreach (var item in values)
{
sheet.SetValue(rowIndex, i, item);
param namei++;
}
}
/// <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(155, 155, 155);
using (ExcelRange rng = ws.Cells[1, 1, rowCount + 1, colCount])
{
rng.Style.Font.Name = "宋体";
rng.Style.Font.Size = 10;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid;  //设置图案的背景为Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(255, 255, 255));
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);
}
// 格式化标题⾏
using (ExcelRange rng = ws.Cells[1, 1, 1, colCount])
{
rng.Style.Font.Bold = true;
rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(234, 241, 246));            rng.Style.Font.Color.SetColor(Color.FromArgb(51, 51, 51));
}
}
public void Dispose()
{
ExcelPackage.Dispose();
if (fs != null)
{
fs.Dispose();
fs.Close();
}
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。