ECharts圖表導入Excel


一、獲取Echarts圖片數據

 
         
//myChart為全局變量,圖表對象;getDataURL方法用來獲取圖片數據,默認圖片格式為"png",可以根據需要設置
var imgData = myChart.getDataURL();

二、后台處理

 2.1 引用NPOI

2.2 獲取數據流

//get the image data and trim "data:image/png;base64,".
string imgData = Request.Form["imgData"];
imgData = imgData.Split(',')[1];
Byte[] bytes = Convert.FromBase64String(imgData);

2.3 寫入excle文件

2.2.1 xls文件

 
         
//create a hssworkbok
HSSFWorkbook sheets = new HSSFWorkbook();
//create a sheet
HSSFSheet sheet1 = (HSSFSheet)sheets.CreateSheet("your sheet's name");
//create a patriarch
HSSFPatriarch patriarch = (HSSFPatriarch)sheet1.CreateDrawingPatriarch();
//create a anchor
HSSFClientAnchor anchor = new HSSFClientAnchor();
//load the picture and get the picture index in the workbook
int pictIndx = sheets.AddPicture(bytes, PictureType.PNG);
//create a picture
HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictIndx);
//Reset the image to the original size.
pict.Resize();
//set the file path
string filePath = "your file path";//relative file path
//write to file
using (FileStream fs = new FileStream(System.Web.HttpContext.Current.Server.MapPath(filePath), FileMode.Create))
{
  sheets.Write(fs);
}

2.2.2 xlsx文件

//create a workbook.
XSSFWorkbook sheets = new XSSFWorkbook();
//create a sheet.
ISheet sheet1 = sheets.CreateSheet("your sheet's name");
//create a patriarch.
XSSFDrawing patriarch = (XSSFDrawing)sheet1.CreateDrawingPatriarch();
//create a anchor.
XSSFClientAnchor anchor = new XSSFClientAnchor();
//load the picture and get the picture index in the workbook.
int pictIdx = sheets.AddPicture(bytes, XSSFWorkbook.PICTURE_TYPE_PNG);
//create a picture.
IPicture pict = patriarch.CreatePicture(anchor, pictIdx);
//reset the image to the original size.
pict.Resize();
//set the file path
string filePath = "your file path";//relative file path
//write to file
using (FileStream fs = new FileStream(System.Web.HttpContext.Current.Server.MapPath(filePath), FileMode.Create))
{
  sheets.Write(fs);
}

2.4 下載

將文件路徑傳到前端href或src,觸發瀏覽器下載。

效果圖如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM