views:

817

answers:

5

Hi,

I have some content that i have to render as a excel file in browser. I was able to render a grid content to excel with the below code.

  Response.Clear();
  Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
  Response.Charset = "";
  Response.ContentType = "application/vnd.xls";
  System.IO.StringWriter stringWrite = new System.IO.StringWriter();
  System.Web.UI.HtmlTextWriter htmlWrite =
  new HtmlTextWriter(stringWrite);
  GridView1.RenderControl(htmlWrite);
  htmlWrite.Write(stringWrite);
  Response.Write(stringWrite.ToString());
  Response.End();

Now i have to do a similar thing for a image. That is, i want a code that can render a image to excel.

I mean when the user opens the excel he should be able to see the image in it.

Is it possible to convert the image to base64sting format and put it into the excel?

Please let me know if you have any idea similar to this.

Thanks Vinod T.

+1  A: 

I've been using the same kind of hacks to get grid data (html tagged) into excel.

If it is HTML data you are writing there, just add <IMG SRC="MYFILENAME.JPG> into the HTML text where you want the images.

What will happen, is that Excel will ask your server (asp.net app) for that file.

You might have to add a full path to the image <IMG SRC="http://myserver/subpath/MYFILENAME.JPG&gt;

Using a packet sniffer, I have verified that Excel in deed will ask for the IMG file, so just make sure you have placed the image ready for download. (either as an asp.net stream) or physically.

My test HTML.
<html>
<table>
<tr><td>test</td><td>test</td<td>test</td></tr>
<tr><td>test</td><td>test</td><td>test</td></tr>
<tr><td>test</td><td>test</td><td><img src="http://myserver/LALLAALLAA.jpg">&lt;/td>&lt;/tr>
</table>
</html>

If ONLY Image, its the same as over only with no table tags at all. Just the HTML and IMG tag.

Wolf5
thanks you very much... this is working... my next task is to render a multipage excel file... can you please let me know some ideas if you have tried something like this before?
Vinodtiru
A: 

Oh. Another more complex way would be to create a .MHT file (webarchive) file. That contain both the HTML and images embedded in the same file. That way you only have one stream out. But I dont know if Excel will recognize the MHT content and show it.

Wolf5
A: 

Office 2007 documents (Word, PowerPoint and Excel) are based on the OpenXML Formats. They are just zip files with a bunch of XML and binary parts (like images) inside. You can create them with any of the XML classes in the Framework and then put the pieces together with the Packaging API (System.IO.Packaging in WindowsBase.dll).

Check out OpenXMLDeveloper.org for details.

Rob Windsor
A: 

Take a look at http://www.codeplex.com/OpenXMLViewer. Perhaps this can help you.

A: 

I use this library for xls-output: CarlogAG Excel Writer

MZywitza