EPPlus是一个使用Open Office XML(xlsx)文件格式,能读写Excel 2007/2010 文件的开源组件,在导出Excel的时候不需要电脑上安装office。
对需要导出报表的数据进行如下操作:
1.引入EPPlus包,在程序包管理控制台中执行命令安装依赖包:
PM> Install-Package EPPlus.Core -Version 1.5.4
2.创建一个EPPlusHelper类,包括两个方法,导入和读取数据
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace SW163.Infrastructure
public class EPPlusHelpe
private static int i;
/// <summary>
/// 导入数据到Excel中
/// </summary>
/// <param name="fileName"></param>
/// <param name="ds"></param>
public static bool ImportExcel(string fileName, DataSet ds)
if (ds == null || ds.Tables.Count == 0)
return false;
FileInfo file = new FileInfo(fileName);
if (file.Exists)
file.Delete();
file = new FileInfo(fileName);
//在using语句里面我们可以创建多个worksheet,ExcelPackage后面可以传入路径参数
//命名空间是using OfficeOpenXml
using (ExcelPackage package = new ExcelPackage(file))
foreach (DataTable dt in ds.Tables)
//创建工作表worksheet
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(dt.TableName);
//给单元格赋值有两种方式
//worksheet.Cells[1, 1].Value = "单元格的值";直接指定行列数进行赋值
//worksheet.Cells["A1"].Value = "单元格的值";直接指定单元格进行赋值
worksheet.Cells.Style.Font.Name = "微软雅黑";
worksheet.Cells.Style.Font.Size = 12;
worksheet.Cells.Style.ShrinkToFit = true;//单元格自动适应大小
for (int i = 0; i < dt.Rows.Count; i++)
for (int j = 0; j < dt.Columns.Count; j++)
worksheet.Cells[i + 1, j + 1].Value = dt.Rows[i][j].ToString();
using (var cell = worksheet.Cells[1, 1, 1, dt.Columns.Count])
//设置样式:首行居中加粗背景色
cell.Style.Font.Bold = true; //加粗
cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; //水平居中
cell.Style.VerticalAlignment = ExcelVerticalAlignment.Center; //垂直居中
cell.Style.Font.Size = 14;
cell.Style.Fill.PatternType = ExcelFillStyle.Solid; //背景颜色
cell.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(128, 128, 128));//设置单元格背景色
//保存
package.Save();
return true;
/// <summary>
/// 读取Excel数据
/// </summary>
/// <param name="fileName"></param>
public static string ReadExcel(string fileName)
StringBuilder sb = new StringBuilder();
FileInfo file = new FileInfo(fileName);
try
using (ExcelPackage package = new ExcelPackage(file))
var count = package.Workbook.Worksheets.Count;
for (int k = 1; k <= count; k++) //worksheet是从1开始的
var workSheet = package.Workbook.Worksheets[k];
sb.Append(workSheet.Name);
sb.Append(Environment.NewLine);
int row = workSheet.Dimension.Rows;
int col = workSheet.Dimension.Columns;
for (int i = 1; i <= row; i++)
for (int j = 1; j <= col; j++)
sb.Append(workSheet.Cells[i, j].Value.ToString() + "\\t");
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
catch (Exception ex)
return "An error had Happen";
return sb.ToString();
3.在需要使用的地方调用
public ExportController(ISignRepository signRepository
,IUserRepository userRepository
,Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment )
SignRepository = signRepository;
UserRepository = userRepository;
HostingEnvironment = hostingEnvironment;
public ISignRepository SignRepository get;
public IUserRepository UserRepository get;
public Microsoft.AspNetCore.Hosting.IHostingEnvironment HostingEnvironment get;
public IActionResult Index()
return View();
public async Task<IActionResult> QueryMethod()
if (!string.IsNullOrEmpty(Request.Form["startingTime"]) && !string.IsNullOrEmpty(Request.Form["EndTime"]))
var starTime = Request.Form["startingTime"].ToString();
var EndTime = Request.Form["EndTime"].ToString();
var EndTimes = EndTime + " " + "23:59:59";
var model = await SignRepository.GetListEntitiesAsync(it => it.Workstatus == 1 && it.Searchtime >= Convert.ToDateTime(starTime) &&it.Searchtime<= Convert.ToDateTime(EndTimes));
if (model.Count > 0)
//创建数据列表
DataTable dataTable = new DataTable();
dataTable.Columns.Add("会员名称", typeof(string));
dataTable.Columns.Add("开始时间", typeof(string));
dataTable.Columns.Add("结束时间", typeof(string));
dataTable.Columns.Add("打卡次数", typeof(string));
DataRow row1 = dataTable.NewRow();
row1["会员名称"] = "会员名称";
row1["开始时间"] = "开始时间";
row1["结束时间"] = "结束时间";
row1["打卡次数"] = "打卡次数";
dataTable.Rows.Add(row1);
var usermodel = await UserRepository.GetListEntitiesAsync(it => true);
if (usermodel.Count > 0)
foreach (var item in usermodel)
int Count = 0;
foreach (var items in model)
if (items.Searchuser == item.Id)
Count += 1;
DataRow row = dataTable.NewRow();
row["会员名称"] = item.UserName;
row["开始时间"] = starTime;
row["结束时间"] = EndTime;
row["打卡次数"] = Count;
dataTable.Rows.Add(row);
// 创建 DataSet 对象
DataSet dataSet = new DataSet("MyDataSet");
dataSet.Tables.Add(dataTable);
string folder = HostingEnvironment.WebRootPath;
string year = Convert.ToDateTime(starTime).ToString("yyyy");
string moon = Convert.ToDateTime(starTime).ToString("MM");
string xlsname = year + "年" + moon + "月打卡记录生成日" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
string fileName = Path.Combine(folder, "Excel", xlsname);
bool result = EPPlusHelpe.ImportExcel(fileName, dataSet);
if (result)
return Content("<script >parent.layer.msg(\'生成成功!\');window.location.href =\'/Export/Index\';</script >", "text/html");
return Content("<script >parent.layer.msg(\'操作失败!\');history.go(-1);</script >", "text/html");
4.用列表来展示生成的报表
//列表
public IActionResult GetList()
try
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(HostingEnvironment.WebRootPath + "/Excel/");
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(string));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Stime", typeof(System.DateTime));
dt.Columns.Add("NameSize", typeof(string));
DataRow dr = dt.NewRow();
if (Directory.Exists(HostingEnvironment.WebRootPath + "/Excel/"))
foreach (System.IO.FileInfo fi in dir.GetFiles())
if (fi.Extension.ToLower() == ".xlsx")
dr = dt.NewRow();
dr[0] = fi.Name;
dr[1] = fi;
dr[2] = fi.CreationTime;
dr[3] = (fi.Length / 1024).ToString() + "KB";
dt.Rows.Add(dr);
DataView dv = dt.DefaultView;
dv.Sort = "Stime DESC";
dt = dv.ToTable();
List<xlsModel> list = new List<xlsModel>();
if (dt.Rows.Count > 0)
for (int i = 0; i < dt.Rows.Count; i++)
xlsModel model = new xlsModel();
model.Id = dt.Rows[i]["Id"].ToString();
model.Name = dt.Rows[i]["Name"].ToString();
model.NameSize = dt.Rows[i]["NameSize"].ToString();
model.Stime = Convert.ToDateTime(dt.Rows[i]["Stime"].ToString());
list.Add(model);
return Json(new code = 0, msg = "成功", count = dt.Rows.Count, data = list );
catch (System.Exception ex)
return Json(new code = 200, msg = "获取数据失败!", count = 0, data = ex );
//删除
public IActionResult Del(string Ids)
bool ret = false;
if (!string.IsNullOrEmpty(Ids))
string[] msg = Ids.Split(\',\');
dynamic[] id = null;
if (msg.Length > 0)
id = new dynamic[msg.Length];
for (int i = 0; i < msg.Length; i++)
id[i] = HostingEnvironment.WebRootPath + "/Excel/" + msg[i];
System.IO.FileInfo file = new System.IO.FileInfo(id[i]);
if (file.Exists)
file.Delete();
ret = true;
if (ret)
return Json(new Msg = "操作成功!" );
return Json(new Msg = "操作失败!" );
xlsModel类
public class xlsModel
public string Id get; set;
public string Name get; set;
public string NameSize get; set;
public DateTime Stime get; set;
五.效果展示
参考:https://www.cnblogs.com/cxt618/p/10451602.html
1.引入EPPlus.dll,旧版的是OfficeOpenXml.dll,最好使用EPPlus
2.调用 string path = UploadExecl(batchUpload.BinaryExcel, "xlsx");,获取上传的xlsx路径
3. 下载Execl
3.1 如果是<a> 标签的连接,可以将方法直接写在 href上就能直接下载
<a href="/FangAn/DetailAuditOutPut/" target="_blank" style="color:#fff;"><el-button type="primary">导出Execl</el-button></a>
后台方法调用:
byte[] result = GetExcelByte(model);
返回值为 File();
return File(result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", model.OrderName + ".xlsx");
3.2 如果是js异步操作,需要下载的话:
后台方法调用:
byte[] result = GetExcelByte(dt, modelReturn.errMessage);
string basestr = Convert.ToBase64String(result);
返回值为base64的字符串
return basestr;
而前台,在需要多加一步操作,可以直接下载:
//res.data 为异步返回值,就是basestr
window.location.href = "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," + res.data;
/// <summary>
/// datatable导出
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public byte[] GetExcelByte(DataTable dt, string err)
{
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet workSheet = package.Workbook.Worksheets.Add("候车亭批量导入");
workSheet.Cells[1, 1].Value = "媒体类型*";
workSheet.Cells[1, 2].Value = "类型子类*";
workSheet.Cells[1, 3].Value = "媒体位置*";
for (int i = 1; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
workSheet.Cells[i + 1, 1].Value = dr[0];
workSheet.Cells[i + 1, 2].Value = dr[1];
workSheet.Cells[i + 1, 3].Value = dr[2];
}
return package.GetAsByteArray();
}
}
/// <summary>
/// execl转成table
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public DataTable ExcelToTable(string path)
{
DataTable vTable = new DataTable();
FileInfo existingFile = new FileInfo(path);
try
{
FileInfo file = new FileInfo(path);
using (ExcelPackage package = new ExcelPackage(file))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int vSheetCount = package.Workbook.Worksheets.Count;
//获取总Sheet页
int maxColumnNum = worksheet.Dimension.End.Column;//最大列
int minColumnNum = worksheet.Dimension.Start.Column;//最小列
int maxRowNum = worksheet.Dimension.End.Row;//最小行
int minRowNum = worksheet.Dimension.Start.Row;//最大行
DataColumn vC;
for (int j = 1; j <= maxColumnNum; j++)
{
vC = new DataColumn("A_" + j, typeof(string));
vTable.Columns.Add(vC);
}
for (int n = 1; n <= maxRowNum; n++)
{
DataRow vRow = vTable.NewRow();
for (int m = 1; m <= maxColumnNum; m++)
{
vRow[m - 1] = worksheet.Cells[n, m].Value;
}
vTable.Rows.Add(vRow);
}
}
}
catch (Exception vErr)
{
Console.WriteLine(vErr.Message);
}
return vTable;
}
/// <summary>
/// 把二进制流转成文件
/// </summary>
/// <param name="path">二进制流,类似(data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,)开头的字符串</param>
/// <param name="path">文件扩展名</param>
/// <returns></returns>
public string UploadExecl(string path, string extension)
{
string sPath = host.ContentRootPath + "\\BatchUpload";//保存的路径
if (!Directory.Exists(sPath))
{
Directory.CreateDirectory(sPath);
}
var regex = new Regex(@"data:(?<mime>[\w/\-\.]+);(?<encoding>\w+),(?<data>.*)", RegexOptions.Compiled);
var match = regex.Match(path);
var mimeType = match.Groups["mime"].Value;
var encodingCode = match.Groups["encoding"].Value;
var data = match.Groups["data"].Value;
byte[] targetFileByte = Convert.FromBase64String(data);
string[] mimeExtension = mimeType.Split(‘/‘);
string fileExtension = extension;
Random random = new Random();
//文件保存
string fileName = string.Format("{0:yyyyMMddHHmmss}{1}", DateTime.Now, random.Next());
string filePath = string.Format("{0}\\{1}.{2}", sPath, fileName, fileExtension);
FileStream file = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write);
file.Write(targetFileByte,0, targetFileByte.Length);
file.Close();
return filePath;
}