将页面导出为带有徽标图像的Excel

时间:2011-02-17 13:19:40

标签: c# html image export-to-excel

我必须将一些数据从asp.net页面导出到excel,所以我基本上使用一个表来创建我需要的自定义标题然后是GridView。导出到Excel时,所有数据都会正确显示,但是当我将徽标图像添加到html时,导出时它不会显示在Excel文件中。

由于我需要将它导出到Excel 2007或更高版本,我知道我可以使用Microsoft的Open XML东西来导出数据,问题是我已经在代码上完成了所有工作,我想知道是否有是另一种方法,而不是使用Open XML重做。

如果没有使用Open XML没有办法做到这一点,有人能告诉我如何将数据导出到它吗?我尝试了一次,但没有取得多大成功。 = /

是的,我正在使用C#。

提前致谢!

我已经更新了代码,现在它看起来像这样,但我仍然看不到图像... = /

    System.IO.StringWriter stringWrite = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
    frmPlanoAcao.RenderControl(htmlWrite);

    StringWriter w = new StringWriter();
    HtmlTextWriter t = new HtmlTextWriter(w);
    imgLogo.RenderControl(t);
    var byte_array = System.Text.Encoding.ASCII.GetBytes(w.ToString());
    Response.Write(stringWrite.ToString());

    this.EnableViewState = false;

    Response.Clear();
    Response.Buffer = false;
    Response.Charset = "ISO-8859-1";
    Response.ContentEncoding = System.Text.Encoding.GetEncoding(1252);
    Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "plano_acao.xls"));
    Response.ContentType = "application/vnd.ms-excel";
    Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
    Response.Write(getExcelStyling());
    Response.OutputStream.Write(byte_array, 0, byte_array.Length);
    Response.Write(stringWrite.ToString());
    Response.Write("</body>");
    Response.Write("</html>");
    Response.End();

3 个答案:

答案 0 :(得分:2)

尝试以下代码。我已经在local IIS进行了测试,但它运行正常。 在网格数据的顶部包含Header Image/Logo之类的图像。

Response.ContentType = "application/vnd.ms-excel";        
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls;");                
StringWriter stringWrite = new StringWriter();        
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);        
dgrExport.DataSource = dtExport;        
dgrExport.DataBind();
dgrExport.RenderControl(htmlWrite);
string headerTable = @"<Table><tr><td><img src=""D:\\Folder\\1.jpg"" \></td></tr></Table>";
Response.Write(headerTable);
Response.Write(stringWrite.ToString());        
Response.End();

您可以根据自己的要求自定义图像的高度和宽度。 <TD>标记需要相同的高度和宽度设置。

答案 1 :(得分:0)

您必须在StringWriter中获取图像,并在字节数组中使用System.Text.Encoding.ASCII.GetBytes(stringwriter string)。 然后将这些写为outputStream.Write(byte_array,0,byte_array.Length); 其中outputstream是HttpContext Response outputstream。

如果你说,要转换网格,图像,一切都进入Excel,我还没试过。但是,我可以说,你可以按照他们的方式将它们分别放入Excel中。

答案 2 :(得分:0)

如果您正在使用C#并想要导出到Excel,我会推荐EPPLUS

http://epplus.codeplex.com/

现在和将来都会为你省去很多麻烦。