【问题标题】:Create and save xls files in c#在 C# 中创建和保存 xls 文件
【发布时间】:2009-11-13 21:00:01
【问题描述】:

我正在尝试像这样使用 c# 创建一个 xls 文件

protected void ExportToExcel(DataSet dset, int TableIndex, HttpResponse Respone, string Felename)
    {
        Respone.Clear();
        Respone.Charset = "";
        Respone.ContentType = "application/vnd.ms-excel";
        Respone.AddHeader("content-disposition", "attachment; filename=" + Felename + ".xls");
        System.IO.StringWriter sw = new System.IO.StringWriter();

        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
        GridView gv = new GridView();
        gv.DataSource = dset.Tables[TableIndex];
        gv.DataBind();
        gv.RenderControl(hw);
        Respone.Write(sw.ToString());
        Respone.End();
    }

它对我来说很好用。但是在成功完成后打开创建的 xls 文件。但我想将文件保存在我的文件夹中,而无需打开并询问我的许可。

如何自动保存..

提前致谢

【问题讨论】:

标签: c# excel


【解决方案1】:

将内容类型更改为 application/x-unknown - 根据浏览器,这应该只提供一个保存选项,因为它不会将其识别为 Excel 文件。

另外,请注意,您实际上只是保存了一个带有 Excel 扩展名的 HTML 文件,它不是真正的 Excel 文件。

【讨论】:

  • 哦,那么还有其他方法可以将我的数据集导出到 excel 文件吗?你能给我一个示例代码吗
  • 您要么需要使用 Excel 互操作,要么购买第三方组件来执行此操作。 HTML方式会在一定程度上起作用。
【解决方案2】:

SpreadsheetGear for.NET 可以从 DataTable 保存到 Excel 工作簿。

请参阅 SpreadsheetGear ASP.NET Excel 报告示例页面 here 上的 DataTable 到 Excel 工作簿 C# 或 VB 示例。

如果您想自己尝试,可以下载免费试用版here

免责声明:我拥有 SpreadsheetGear LLC

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    相关资源
    最近更新 更多