lenlenya
3/22/2018 - 9:57 AM

通过使用Xslt来导出excel数据

通过使用Xslt来导出excel数据

public void Export()
{
    int yearMonth;
    if (int.TryParse(ddlPeriod.SelectedValue, out yearMonth))
    {
        AnalyzeReports = _projectFeeService.GetProjectFeeAnalyze(txtMixCondition.Text, int.Parse(ddlPeriod.SelectedValue));
    }
    else
    {
        AnalyzeReports = new List<ProjectFeeAnalyzeReport>(0);
    }
    XslCompiledTransform xslt = new XslCompiledTransform();
    xslt.Load(Server.MapPath("~/ExportTemplate/ProjectFeeAnalyze.xslt"), new XsltSettings(true, true), new XmlUrlResolver());

    XmlSerializer serializer = new XmlSerializer(AnalyzeReports.GetType());
    using (MemoryStream stream = new MemoryStream())
    {
        XmlWriterSettings xmlWritersettings = new XmlWriterSettings()
        {
            Indent = true,
            Encoding = Encoding.UTF8,
            IndentChars = " ",
            OmitXmlDeclaration = true,
        };
        using (XmlWriter xmlWriter = XmlWriter.Create(stream, xmlWritersettings))
        {
            serializer.Serialize(xmlWriter, AnalyzeReports);
        }

        stream.Position = 0;
        using (XmlReader reader = XmlReader.Create(stream))
        {
            reader.MoveToContent();
            using (MemoryStream results = new MemoryStream())
            {
                xslt.Transform(reader, null, results);

                Response.Clear();
                Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}", HttpUtility.UrlEncode("项目预算执行情况分析.xls")));
                Response.ContentType = "application/ms-excel";
                Response.Charset = "utf-8";
                Response.ContentEncoding = Encoding.UTF8;
                Response.BinaryWrite(results.GetBuffer());
                Response.End();
            }
        }
    }
}
//更多关于将实体实例化为xml的文章,参看:http://www.cnblogs.com/weblogical/archive/2013/05/22/3093295.html