如何使用 ASP.net MVC 3 FileStreamResult 返回 .net 代码中生成的文本?

发布于 2025-01-08 17:54:42 字数 900 浏览 1 评论 0原文

在 ASP.net webforms 中,我曾经编写代码,通过将内容类型设置为“application/vnd.ms-excel”,使浏览器加载 Excel 中的表格,效果非常好。现在,我正在尝试找到在 .net 中执行此操作的最佳方法。

我编写了一些如下所示的 .net 代码:

public FileStreamResult TaskforceDetailExcelData(string taskforceIdsCommaSeparated)
{
    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    System.IO.StreamWriter sw = new System.IO.StreamWriter(ms);
    sw.Write("<html><head></head><body><table>...</table></body></html>");
    return new FileStreamResult(ms, "application/vnd.ms-excel");
}

结果是我在浏览器中得到以下内容:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=Content-Type content="text/html; charset=windows-1252"></HEAD>
<BODY></BODY></HTML>

我需要做什么才能使用 excel 响应类型将我的表提供给浏览器?

In ASP.net webforms, I used to write code to make the browser load a table in Excel by setting the content type to 'application/vnd.ms-excel' and it worked very well. Now, I'm trying to find the best way to do this in .net.

I've written some .net code that looks like this:

public FileStreamResult TaskforceDetailExcelData(string taskforceIdsCommaSeparated)
{
    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    System.IO.StreamWriter sw = new System.IO.StreamWriter(ms);
    sw.Write("<html><head></head><body><table>...</table></body></html>");
    return new FileStreamResult(ms, "application/vnd.ms-excel");
}

The result is that I get the following in the browser:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=Content-Type content="text/html; charset=windows-1252"></HEAD>
<BODY></BODY></HTML>

What do I need to do to get my table served to the browser with an excel response type?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

遗忘曾经 2025-01-15 17:54:42

试试这个代码。 (未经测试,但类似于我对 text/csv mime 类型所做的操作)

public FileResult Export()
{
  var csv = "<html><head></head><body><table>...</table></body></html>";
  System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
  byte[] result = encoding.GetBytes(csv);
  return File(result, "application/vnd.ms-excel", "segnalazioni.csv");
}

try this code. (not tested, but similar to what I do with a text/csv mime type)

public FileResult Export()
{
  var csv = "<html><head></head><body><table>...</table></body></html>";
  System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
  byte[] result = encoding.GetBytes(csv);
  return File(result, "application/vnd.ms-excel", "segnalazioni.csv");
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文