天天看點

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