ASP.NET epplus 產生excel包含網路圖片跟下載excel
功能不難
做法如下:
1-先從nuget下載epplus
2-找出網路圖片的正確網址,把它填入fileURL
3-指定圖片在excel的大小跟位置
3-將excel改成GetAsByteArray
4-用Response另存在使用者電腦中
protected void btn2_Click(object sender, EventArgs e)
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial; // 關閉新許可模式通知
// 沒設置的話會跳出 Please set the excelpackage.licensecontext property
//檔案名稱
var fileName = "ExampleExcel" + DateTime.Now.ToString("yyyy-MM-dd--hh-mm-ss") + ".xlsx";
var file = new FileInfo(fileName);
using (var excel = new ExcelPackage(file))
{
// 建立分頁
var ws = excel.Workbook.Worksheets.Add("list" + DateTime.Now.ToShortDateString());
// 寫入資料試試
ws.Cells[2, 1].Value = "測試測試";
WebClient MyWebClient = new WebClient();
//網路圖片
string fileURL = "https://********.png";
Byte[] pageData = MyWebClient.DownloadData(fileURL);
MemoryStream fs = new MemoryStream();
fs.Write(pageData, 0, pageData.Length - 1);
var imgfs = System.Drawing.Image.FromStream(fs);
fs.Close();
ExcelPicture picture = excel.Workbook.Worksheets[0].Drawings.AddPicture("logo", imgfs);//插入圖片
picture.SetPosition(100, 100);//設置圖片的位置
picture.SetSize(100, 100);//設置圖片的大小
//儲存Excel
//Byte[] bin = excel.GetAsByteArray();
//File.WriteAllBytes(@"C:\TEMP\" + fileName, bin);
//儲存和歸來的Excel檔案作為一個ByteArray
var data = excel.GetAsByteArray();
HttpResponse response = HttpContext.Current.Response;
Response.Clear();
//輸出標頭檔案
Response.AddHeader("content-disposition", "attachment; filename="+fileName+"");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.BinaryWrite(data);
Response.Flush();
Response.End();
//package.Save();//這個方法是直接下載到本地
}
自我LV~