0

I am using the below code to export excel. htmlData is html data that is generated at client side. I have written this method in Api controller.

public HttpResponseMessage ExportXls(string htmlData)
{
    try
    {
        byte[] excelData =  Encoding.ASCII.GetBytes(htmlData.Trim());

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        var stream = new MemoryStream(excelData);
        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "Data.xls"
        };
        return result;
    }
}

I am getting warning for format of xls file while opening file. Is there any workaround for that?

I also wanted to ask if there was any method to export excel without getting any warning but without using any third party dlls like eppplus and closedXML.

Is anyone able to generate excel without warning by using only Response?

2 Answers2

0

https://blogs.msdn.microsoft.com/vsofficedeveloper/2008/05/08/office-2007-file-format-mime-types-for-http-content-streaming-2/

You want to specify the right mime type it looks then.

i.e application/vnd.ms-excel

This might also be useful, What is a correct mime type for docx, pptx etc?

Worth also looking at

the file you are trying to open is in a different format than specified by the file extension in Asp.Net

This might help you out.

Community
  • 1
  • 1
JamesKn
  • 1,035
  • 9
  • 16
  • @VikasChauhan added an extra link to the answer if this helps this will become a duplicate question if it helps. http://stackoverflow.com/questions/16144900/the-file-you-are-trying-to-open-is-in-a-different-format-than-specified-by-the-f – JamesKn Mar 06 '17 at 13:34
  • Thanks @JamesKn will try this tomorrow. – Vikas Chauhan Mar 06 '17 at 14:27
  • For using closedXml or another third party I would have to convert html and that would take time. Used the "application/octet-stream" but still not working. – Vikas Chauhan Mar 07 '17 at 04:04
0

I sent the html data in csv format to server. Used split functions to add them to closedXml cells and was able to generate excel successfully in xlsx format.