380 lines
13 KiB
C#
380 lines
13 KiB
C#
using OfficeOpenXml;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.Drawing;
|
||
using System.IO;
|
||
using System.Linq;
|
||
using System.Data;
|
||
using System.Text;
|
||
using System.Threading.Tasks;
|
||
using System.Drawing.Drawing2D;
|
||
using System.ComponentModel;
|
||
using OfficeOpenXml.Style;
|
||
|
||
namespace JY.Utility
|
||
{
|
||
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>
|
||
/// 将List集合导出到Excel中
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="list"></param>
|
||
/// <param name="sheetName"></param>
|
||
public void ExportList<T>(IEnumerable<T> list, string sheetName = "")
|
||
{
|
||
if (string.IsNullOrEmpty(sheetName))
|
||
{
|
||
sheetName = ExcelPackage.File.Name;
|
||
}
|
||
AppendSheetToWorkBook(list, sheetName);
|
||
Save();
|
||
}
|
||
|
||
/// <summary>
|
||
/// 将List集合导出到Excel中
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="dt"></param>
|
||
/// <param name="sheetName"></param>
|
||
public void ExportDataTable(string strFileName,DataTable dt)
|
||
{
|
||
AppendSheetToWorkBook(strFileName,dt);
|
||
Save();
|
||
}
|
||
|
||
/// <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(string strFileName,DataTable sourceTable)
|
||
{
|
||
AppendSheetToWorkBook(strFileName,sourceTable, true);
|
||
}
|
||
|
||
/// <summary>
|
||
/// DataTable数据导出到Excel(xlsx)
|
||
/// </summary>
|
||
/// <param name="ExcelPackage">ExcelPackage</param>
|
||
/// <param name="sourceTable">数据源</param>
|
||
/// <param name="isDeleteSameNameSheet">是否删除同名的sheet</param>
|
||
public void AppendSheetToWorkBook(string strFileName,DataTable sourceTable, bool isDeleteSameNameSheet)
|
||
{
|
||
//创建worksheet
|
||
ExcelWorksheet ws = AddSheet(strFileName, isDeleteSameNameSheet);
|
||
//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, msg);
|
||
|
||
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);
|
||
i++;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 保存修改
|
||
/// </summary>
|
||
public void Save()
|
||
{
|
||
try
|
||
{
|
||
ExcelPackage.Save();
|
||
ExcelPackage.Stream.Close();
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
throw ex;
|
||
}
|
||
|
||
}
|
||
|
||
/// <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));
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// <summary>
|
||
/// 导入Excel(EPPlus只支持.xlsx)
|
||
/// </summary>
|
||
/// <param name="sheetindex">第几个Sheet</param>
|
||
/// <returns></returns>
|
||
public DataTable ImportExcel(int sheetindex = 1)
|
||
{
|
||
DataSet ds = new DataSet();
|
||
using (ExcelWorksheet worksheet = ExcelPackage.Workbook.Worksheets[sheetindex])
|
||
{
|
||
if (worksheet.Dimension == null)
|
||
{
|
||
return null;
|
||
}
|
||
DataTable table = new DataTable(worksheet.Name);
|
||
for (int rowNum = 1; rowNum <= worksheet.Dimension.End.Row; rowNum++)
|
||
{
|
||
|
||
#region 创建列
|
||
if (table.Columns.Count == 0)
|
||
{
|
||
#region 第一行数据作为表头
|
||
for (int columnNum = 1; columnNum <= worksheet.Dimension.End.Column; columnNum++)
|
||
{
|
||
table.Columns.Add(worksheet.Cells[rowNum, columnNum].Value.ToString().Trim(), typeof(string));
|
||
}
|
||
continue;
|
||
#endregion
|
||
}
|
||
#endregion
|
||
|
||
#region 新增行
|
||
DataRow dr = table.NewRow();
|
||
for (int columnNum = 1; columnNum <= table.Columns.Count; columnNum++)
|
||
{
|
||
if (worksheet.Cells[rowNum, columnNum].Value==null)
|
||
{
|
||
dr[columnNum - 1] =string.Empty;
|
||
}
|
||
else
|
||
{
|
||
dr[columnNum - 1] = worksheet.Cells[rowNum, columnNum].Value.ToString().Trim();
|
||
}
|
||
|
||
}
|
||
table.Rows.Add(dr);
|
||
#endregion
|
||
}
|
||
return table;
|
||
}
|
||
|
||
}
|
||
|
||
public void Dispose()
|
||
{
|
||
ExcelPackage.Dispose();
|
||
if (fs != null)
|
||
{
|
||
fs.Dispose();
|
||
fs.Close();
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|