1.将图片字节转换为图片存储在本地
byte[] bt= chart.GetPicture();
string strUrl = Server.MapPath(".")+"/GifToExcel/Report1.gif";
Response.ContentType = "image/gif";//上传时,存储的图片类型 //输出图片文件二进制数据
Response.OutputStream.Write(bt,0,bt.Length);
System.IO.MemoryStream s = new System.IO.MemoryStream(bt);
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(s);
bitmap.Save(strUrl);
2.将本地图片汇入到Excel的类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ex=Microsoft.Office.Interop.Excel;
using System.Reflection;
/// <summary>
/// ExcelReport 的摘要描述
/// </summary>
public class InsertPictureToExcel
{
/// <summary>
/// 將圖片匯出到Excel
/// </summary>
/// <param name="excelTemple">excel模板路徑</param>
/// <param name="img">要匯入到excel的圖片路徑</param>
/// <param name="position">圖片放到excel的哪個位置</param>
public static void imgToExcel(string excelTemple, string img, string position)
{
object missing = Missing.Value;
//定义一个Excel应用程序
ex.ApplicationClass excelObj = new ex.ApplicationClass();
excelObj.DisplayAlerts = false;
excelObj.Visible = false;
ex.Workbooks wbooks = excelObj.Workbooks;
ex.Workbook wbook = wbooks.Open(HttpContext.Current.Server.MapPath(excelTemple), missing, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing, missing, missing, missing);
ex.Sheets sheets = (ex.Sheets)wbook.Worksheets;
ex._Worksheet sheet = (ex._Worksheet)sheets.get_Item(1);
ex.Range exRange = (ex.Range)sheet.get_Range(position, missing);
exRange.Select();
//声明一个pictures对象,用来存放柱状图
ex.Pictures pics = (ex.Pictures)sheet.Pictures(missing);
//插入图片
pics.Insert(HttpContext.Current.Server.MapPath(img), missing);
string imgName = HttpContext.Current.Server.MapPath(img).Substring(0, HttpContext.Current.Server.MapPath(img).LastIndexOf('.'));
wbook.SaveAs(imgName + ".xlsx", missing, missing, missing, missing, missing,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing,
missing);
wbook.Close(false, missing, missing);
excelObj.Quit();
//必须关闭释放所引用的COM对象,关闭Excel进程,否则会占用服务器资源
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
}
}
3.JavaScript汇出图片到Excel中
<script type="text/javascript">
function fnExportExcel(){
try{
var oXL=new ActiveXObject("Excel.Application");
}catch(e){
alert("Excel沒有安裝或瀏覽器設置不正確,請啟用所有Active控件和插件");
//工具-> Internet??-> 安全->自定???-> ??有??安全??的ActiveX控件?行初始化 ???用
return false;
}
var oWB=oXL.Workbooks.Add();
var oSheet=oWB.ActiveSheet;
oSheet.Cells(1,1).Select();
oSheet.Pictures.Insert(document.getElementById("img1").src);
oXL.Visible = true;
oXL.UserControl = true;
}
</script>
在Web.config的<system.web>里加
<identity impersonate="true"/>
<!-- impersonate 指定是否对每一个请求使用客户端模拟 -->
将图片字节与JavaScript汇入Excel的综合教程
本文详细介绍了如何通过C#将图片字节转换为本地图片存储,然后利用JavaScript将本地图片汇入Excel。同时,提供了一个在Web.config中启用客户端模拟的解决方案,确保了跨浏览器兼容性。
4196

被折叠的 条评论
为什么被折叠?



