SQL Server Image column to html



我有一个表格,其中包含SQL Server表格中的所有员工图片。列的类型为Image

我需要以word格式下载emplyee个人资料,并在其中包含他们的图片。我能够以 HTML 格式导出他们的所有数据,然后使用以下 C# 代码将该 html 转换为 word 并将其作为下载提供。

public static void HtmlToWordDownload(string HTML, string FileName)
{
lock (LockMulti)
{
string strBody = string.Empty;
strBody = @"<html xmlns:o='urn:schemas-microsoft-com:office:office' " +
"xmlns:w='urn:schemas-microsoft-com:office:word'" +
"xmlns='http://www.w3.org/TR/REC-html40'>" +
"<head><title>Document Title</title>" +
"<!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:Zoom>100</w:Zoom>" +
"<w:DoNotOptimizeForBrowser/></w:WordDocument></xml><![endif]-->" +
"<style> @page Section1 {size:8.27in 11.69in; mso-first-footer:ff1; mso-footer: f1; mso-header: h1; " +
//"border:solid navy 2.25pt; padding:24.0pt 24.0pt 24.0pt 24.0pt; " +
"margin:0.6in 0.6in 0.6in 0.6in ; mso-header-margin:.1in; " +
"mso-footer-margin:.1in; mso-paper-source:0;} " +
"div.Section1 {page:Section1;} p.MsoFooter, li.MsoFooter, " +
"div.MsoFooter{margin:0in; margin-bottom:.0001pt; " +
"mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; " +
"font-size:12.0pt; font-family:'Arial';} " +
"p.MsoHeader, li.MsoHeader, div.MsoHeader {margin:0in; " +
"margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center " +
"3.0in right 6.0in; font-size:12.0pt; font-family:'Arial';}--></style></head> ";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.ms-word";
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + FileName + ".doc");
StringBuilder htmlCode = new StringBuilder();
htmlCode.Append(strBody);
htmlCode.Append("<body><div class=Section1>");
htmlCode.Append(HTML);
htmlCode.Append("</div></body></html>");
HttpContext.Current.Response.Write(htmlCode.ToString());
HttpContext.Current.ApplicationInstance.CompleteRequest();
HttpContext.Current.Response.Flush();
}
}

它工作绝对正常。现在我如何将雇员的图片嵌入其中。我应该转换该图像以嵌入到 HTML 中的格式。我尝试了以下查询,但它为所有图片提供了相同的输出。请帮忙。

select 
top 30 convert(varchar, convert(binary, i.Photo)) 
from hrm.hrm_rp_Employee_Image i

输出如下

(No column name)
ÿØÿà
ÿØÿà
ÿØÿà
ÿØÿà
ÿØÿà
ÿØÿà

我的方法是否正确或需要做其他事情?

更新

我发现了以下查询将其转换为base64。

declare @pic varchar(max)
SELECT  @pic = '<img src="data:image/jpg;base64,' + CAST(N'' AS XML).value(
'xs:base64Binary(xs:hexBinary(sql:column("Pic")))'
, 'VARCHAR(MAX)'
) 
FROM (
SELECT CAST(Photo AS VARBINARY(MAX)) AS Pic from hrm.hrm_rp_Employee_Image
) AS h;
set @pic = @pic + '" style="height: 100px; width: 100px;" />' 
print @pic

它成功转换并给了我一个字符串,当我在任何在线 html 编辑器上测试它时,它可以完美运行。

但是下载后它没有显示在我的word文件中,出现了带有红色" X"符号的图像,有人可以告诉我可能是什么问题。

您需要在 C# 中将二进制数据转换为图像,然后将其附加到 HTML 中。

下面的链接将帮助您将二进制数据转换为图像

链接

最新更新