EppPlus

最近在项目中第一次接触到excel部分的东西,所以学习了解了一下EppPlus,首先,引入两篇我觉得写的不错的博文:

介绍详细用法:

http://www.cnblogs.com/liudeyun/p/3535740.html

一个方法,看起来比较受启发,web方面的保存等:

http://www.cnblogs.com/olartan/archive/2012/07/14/2591711.html

之后,官网的网址及官网的WebapplicationExample

http://epplus.codeplex.com/wikipage?title=WebapplicationExample

最后贴出我自己的方法:

public static void ExportExcelFillWithDataByWeb(string filePath,string fileName, string sheetName, IDictionary<string, string> data)
{
try
{
FileInfo file = new FileInfo(filePath);
if (file.Exists)
{
using (var ExcelPlus = new ExcelPackage(file))
{
var sheet = ExcelPlus.Workbook.Worksheets[sheetName];
if (sheet!=null)
{
foreach (var kv in data)
{
sheet.Cells[kv.Key].Value = kv.Value;
}

var httpContext = HttpContext.Current;

httpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
httpContext.Response.ContentEncoding = Encoding.UTF8;
httpContext.Response.Charset = "";
httpContext.Response.AppendHeader(
"Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
httpContext.Response.BinaryWrite(ExcelPlus.GetAsByteArray());
httpContext.Response.Flush();
httpContext.Response.End();
}
else
{
throw new Exception("No Sheet was Found!");
}
}
}
else
{
throw new Exception("No File was Found!");
}
}
catch (Exception ex)
{
throw ex;
}
}

最后,补充一点点:

web项目中的路径问题:

此方法中需要用到一个做好的excel文件模版,获取模版路径的方法是:

 Server.MapPath("virtual path");

注:

HttpRequest hr = System.Web.HttpContext.Current.Request;
string path = hr.CurrentExecutionFilePath;

通过HttpRequest的方法获取的路径为浏览器地址栏里的路径

原文地址:https://www.cnblogs.com/baibjq/p/4442153.html