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?

4
  • what is the warning message? Commented Mar 6, 2017 at 13:11
  • Is it as simple as changing FileName to "Data.xlsx"? Commented Mar 6, 2017 at 13:14
  • @JamesKn the warning is "the file youa re trying to open,"[filename.xls]" is in different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file.Do you want to open a file now?" Commented Mar 6, 2017 at 13:19
  • @heyiamt If I change the format to .xlsx, then file doesn't get open. Commented Mar 6, 2017 at 13:21

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@VikasChauhan added an extra link to the answer if this helps this will become a duplicate question if it helps. stackoverflow.com/questions/16144900/…
Thanks @JamesKn will try this tomorrow.
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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.