下载数据表作为excel 2013文件 [英] Download datatable as excel 2013 file

查看:75
本文介绍了下载数据表作为excel 2013文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的,



我想下载DataTable数据作为Excel 2013文件不是excel 2003.

这是我的代码:< br $>


Dears,

I want to download a DataTable Data as Excel 2013 File Not excel 2003.
Here is my code:

private void DownloadExcelReport(DataTable dtResult)
        {
            var gv = new GridView
            {
                DataSource = dtResult
            };
            gv.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=AllDataReport.xlsx");
            Response.ContentType = "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");            
            StringWriter objStringWriter = new StringWriter();
            HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter);
            gv.RenderControl(objHtmlTextWriter);
            Response.Output.Write(objStringWriter.ToString());
            Response.End();
        }





结果:

文件已下载as .xlsx文件,但我无法打开它。

此消息出现:

Excel无法打开文件,因为扩展名无效,请验证文件是否已损坏,以及文件扩展名与文件格式一致。



我尝试过:



我做了一些搜索,我发现了以下内容:

更改内容类型和响应标题:

//Response.AddHeader (\"content-disposition ,attachment; filename = AllDataReport.xls);

//Response.ContentType =application / ms-excel;



要像这样:

Response.AddHeader(content-disposition,attachment; filename = AllDataReport.xlsx);

Response.ContentType =application / application / vnd.openxmlformats-officedocument.spreadsheetml.sheet;



The Result:
The file is downloaded as .xlsx File but i CANNOT OPEN IT.
This Message Appears:
Excel cannot open the file because the extension is not valid verify that the file is not corrupted and that the file extension matches the format of the file.

What I have tried:

I did some search and i found the following:
Change the content type and response header from this:
//Response.AddHeader("content-disposition", "attachment; filename=AllDataReport.xls");
//Response.ContentType = "application/ms-excel";

To Be Like This:
Response.AddHeader("content-disposition", "attachment; filename=AllDataReport.xlsx");
Response.ContentType = "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

推荐答案

如果您有数据表,您可以使用 DataTable.WriteXML()方法将其保存为xml文件,然后在excel中打开该文件。
If you have a datatable, you can save it as a xml file using the DataTable.WriteXML() method, and then open that file in excel.


这篇关于下载数据表作为excel 2013文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆