C# 打开时收到警告 excel

C# Getting warning while opening excel

我正在使用以下代码导出 excel。 html数据是在客户端生成的html数据。我已经在 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;
    }
}

我在打开文件时收到有关 xls 文件格式的警告。有什么解决方法吗?

我还想问一下是否有任何方法可以导出 excel 而不会收到任何警告但不使用任何第三方 dll,如 eppplus 和 closedXML。

是否有人能够仅使用 Response 在没有警告的情况下生成 excel?

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

您想指定它看起来正确的 mime 类型。

即application/vnd.ms-excel

这也可能有用, What is a correct mime type for docx, pptx etc?

也值得一看

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

这可能会对您有所帮助。

我将 html 数据以 csv 格式发送到服务器。使用拆分函数将它们添加到 closedXml 单元格中,并能够以 xlsx 格式成功生成 excel。