我使用此代码将URL中的图像插入到Excel文件中,但它在文件中呈现为黑框。
string url = Regex.Match(row[column.ColumnName].ToString(), "<img.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase).Groups[1].Value;
var pic = worksheet.Drawings.AddPicture(Guid.NewGuid().ToString(), ImageUtilities.GetImageFromUrl(url, Request));
pic.SetSize(400,200);
pic.SetPosition(rowIndex, 0, columnIndex, 0);
我已验证从服务器返回的图像是否有效(我已将其保存到文件系统并打开它)以下是获取图像的代码。
public static Image GetImageFromUrl(string url, HttpRequestBase request) {
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
if (request != null) {
httpWebRequest.CookieContainer = new CookieContainer();
// add auth cookie and session cookie so graphs/etc will render correctly
if (request.Cookies[FormsAuthentication.FormsCookieName] != null) {
var oldCookie = request.Cookies[FormsAuthentication.FormsCookieName];
var cookie = new Cookie(oldCookie.Name,oldCookie.Value, oldCookie.Path,"localhost");
httpWebRequest.CookieContainer.Add(cookie);
}
if (request.Cookies[PROVIDERPORTALSESSION_COOKIE] != null) {
var oldCookie = request.Cookies[PROVIDERPORTALSESSION_COOKIE];
var cookie = new Cookie(oldCookie.Name, oldCookie.Value, oldCookie.Path, "localhost");
httpWebRequest.CookieContainer.Add(cookie);
}
}
using (HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse()) {
using (Stream stream = httpWebReponse.GetResponseStream()) {
var image= Image.FromStream(stream);
return image;
}
}
}