我的网站上有一个网页,允许我从该页面下载图表并将其添加到Excel工作表中。但是,会显示一个带有“当前无法显示此图像”字样的红色x按钮代替图表。我在网上尝试了很多解决方案,但所有这些解决方案都有相同的结果。
以下是我的代码:
protected void ExcelDl_Click(object sender, EventArgs e) {
string tmpChartName = "test2.jpg";
string imgPath = HttpContext.Current.Request.PhysicalApplicationPath + tmpChartName;
Chart1.SaveImage(imgPath);
string imgPath2 = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/" + tmpChartName);
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls;");
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
string headerTable = @"<Table><tr><td><img src='" + imgPath2 + @"' \></td></tr></Table>";
Response.Write(headerTable);
Response.Write(sw.ToString());
Response.End();
}
任何形式的帮助将不胜感激。另请注意,我已在Web.config中添加了所需的代码。
答案 0 :(得分:0)
我们已经尝试过你的程序,在这里工作正常。 Excel随图像一起下载。我已经在iis中安装并尝试使用许多客户端机器,它工作正常。
不确定你的目的是什么。问题可能是错误的图像路径引用会导致此问题。打印图像URL并确保其是否正确。
备用方法:不使用excel单元格内的html标签,而是使用XML结束方法在excel单元格内渲染图像。
这里我添加了Closed XML方法的示例代码,以在excel中呈现图像。使用此代码需要引用以下DLL 1. ClosedXML.dll 2. WindowsCore.dll 3. DocumentFormat.OpenXML.dll 4. PresentationCore.dll
封闭XML方法的参考链接:https://closedxml.codeplex.com/
using (XLWorkbook wb = new XLWorkbook())
{
IXLWorksheet WorkSheet = new IXLWorksheet();
string LogoPath = Server.MapPath("~/App_Themes/Images/logonew.png");
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(LogoPath);
if (bitmap != null)
{
var stream = new System.IO.MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Gif);
if (stream != null)
{
stream.Position = 0;
XLPicture pic = new XLPicture
{
NoChangeAspect = true,
NoMove = true,
NoResize = true,
ImageStream = stream,
Name = "Logo",
EMUOffsetX = 4,
EMUOffsetY = 6
};
XLMarker fMark = new XLMarker
{
ColumnId = 1,
RowId = 1
};
pic.AddMarker(fMark);
WorkSheet.AddPicture(pic);
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=test.xls");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
请检查并告诉我您的意见。