XML结合XSLT生成Excel(导入到多个Worksheet)

1、.aspx

ContractedBlock.gif ExpandedBlockStart.gif Code
ExpandedBlockStart.gifContractedBlock.gif<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExportAsExcel.aspx.cs" Inherits="ExportAsExcel" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>Untitled Page</title>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
        
<asp:Button ID="btnExport" runat="server" OnClick="btnExport_Click" Text="Export" /></div>
    
</form>
</body>
</html>

2、code-behide 

ContractedBlock.gif ExpandedBlockStart.gif Code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Text;

public partial class ExportAsExcel : System.Web.UI.Page
ExpandedBlockStart.gifContractedBlock.gif
{
    
protected void Page_Load(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{

    }

    
    
protected void btnExport_Click(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
string strConn = "server=.;database=AdventureWorks;uid=sa;pwd=chang;";
        SqlConnection conn 
= new SqlConnection(strConn);
        SqlDataAdapter adapter 
= new SqlDataAdapter("select top 100 employeeId, title from HumanResources.Employee order by employeeId; select top 200 productId, name as productName from  Production.Product order by productId", conn);
        DataSet ds 
= new DataSet();

        adapter.Fill(ds);

        
string fileName = System.DateTime.Now.Ticks.ToString();
        
string templatePath = Server.MapPath("Demo.xsl");
        
string objectPath = Server.MapPath(fileName + ".xls");

        ExcelBuilder excel 
= new ExcelBuilder();

        
if (excel.BuildExcel(ds, objectPath, templatePath))
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            rewrite(objectPath);
            DownLoad(Page.Response, objectPath, fileName 
+ ".xls");
        }

    }


    
private void DownLoad(System.Web.HttpResponse response, string filepath, string VirtualName)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
try
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (File.Exists(filepath))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                FileInfo fi 
= new FileInfo(filepath);
                response.Clear();
                response.ClearHeaders();
                response.Buffer 
= false;

                response.AppendHeader(
"Content-Disposition""attachment;filename=" + System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(VirtualName)));
                response.AppendHeader(
"Content-Length", fi.Length.ToString());
                response.ContentType 
= "application/vnd.ms-excel";
                response.WriteFile(filepath);
                response.Flush();

                response.End();
            }

        }

        
catch (Exception)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{

        }

        
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (File.Exists(filepath))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                File.Delete(filepath);
            }

        }

    }


    
private void rewrite(string objectPath)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{       
        
try
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            StreamReader sr 
= new StreamReader(objectPath);
            
string content = sr.ReadToEnd();
            sr.Close();

            StreamWriter sw 
= new StreamWriter(objectPath, false, Encoding.Unicode);
          
            sw.Write(
"<?xml version=\"1.0\"?><?mso-application progid=\"Excel.Sheet\"?>" + content);
            sw.Close();
        }

        
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            Response.Write(ex.Message);
        }

        
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
           
        }


    }

}


3、ExcelBuilder  

ContractedBlock.gif ExpandedBlockStart.gif Code
using System;
using System.Collections.Specialized;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Data;
using System.IO;

public class ExcelBuilder
ExpandedBlockStart.gifContractedBlock.gif
{
    
public ExcelBuilder()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{

    }


    
private void GetXSLFile(DataSet ds, string XslPath, params string[] Titles)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
string strColumn = "";
        
string strRow = "";
        
string dsName = ds.DataSetName;
        
string tableName = ds.Tables[0].TableName;
        
string header = dsName + "/" + tableName;

        
foreach (string title in Titles)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            strColumn 
+= "<th>" + title + "</th>" + "\r\n";
            strRow 
+= "<td>" + "<xsl:value-of select=" + "\"" + title + "\"" + "/>" + "</td>" + "\r\n";
        }


        
string str = @"<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">
        <xsl:template match=""/"">
        <html xmlns:o=""urn:schemas-microsoft-com:office:office"" xmlns:x=""urn:schemas-microsoft-com:office:excel"" xmlns=""http://www.w3.org/TR/REC-html40""> 
        <head> 
        <meta http-equiv=""Content-Type"" content=""text/html;charset=utf-8"" /> 
        <style> 
        .xl24{mso-style-parent:style0;mso-number-format:""\@"";text-align:right;} 
        </style> 
        <xml> 
        <x:ExcelWorkbook> 
        <x:ExcelWorksheets> 
        <x:ExcelWorksheet> 
        <x:Name>Sheet1</x:Name> 
        <x:WorksheetOptions> 
                <x:ProtectContents>False</x:ProtectContents> 
                <x:ProtectObjects>False</x:ProtectObjects> 
                <x:ProtectScenarios>False</x:ProtectScenarios> 
        </x:WorksheetOptions> 
        </x:ExcelWorksheet> 
        </x:ExcelWorksheets> 
        </x:ExcelWorkbook> 
        </xml> 
        </head>  
        <body> 
";
        str 
+= "\r\n" + @"<table border=""1"" cellpadding=""0"" cellspacing=""0""> 
                <tr>
" + "\r\n";
        str 
+= strColumn;
        str 
+= @" </tr> 
                <xsl:for-each select=""
" + header + @""">
                <tr>
";
        str 
+= "\r\n" + strRow;
        str 
+= @"</tr> 
                </xsl:for-each> 
                </table> 
                </body> 
                </html> 
                    
                    
                </xsl:template> 
                </xsl:stylesheet> 
";

        
if (File.Exists(XslPath))
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            File.Delete(XslPath);
        }

        FileStream fs 
= File.Create(XslPath);
        StreamWriter sw 
= new StreamWriter(fs);
        sw.Write(str);
        sw.Close();
        fs.Close();
    }


    
private void GetXmlFile(DataSet ds, string XmlFilePath)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
if (File.Exists(XmlFilePath))
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            File.Delete(XmlFilePath);
        }


        FileStream fs 
= File.Create(XmlFilePath);
        StreamWriter writer 
= new StreamWriter(fs);

        writer.Write(ds.GetXml());
        writer.Close();
        fs.Close();
    }


    
public bool BuildExcel(DataSet ds, string tempPath, string xslPath)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
bool flag = false;

        
if (File.Exists(tempPath))
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            File.Delete(tempPath);
        }


        
string _path = tempPath.Substring(0, tempPath.Length - 4);
        
string _fileXml = _path + ".xml";
        
string _fileXsl = _path + ".xsl";
        
string _fileXls = _path + ".xls";

        
try
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            GetXmlFile(ds, _fileXml);

            XmlDocument doc 
= new XmlDocument();
            doc.Load(_fileXml);

            XslTransform xslt 
= new XslTransform();
            xslt.Load(xslPath);

            XmlElement root 
= doc.DocumentElement;
            XPathNavigator nav 
= root.CreateNavigator();
            XmlTextWriter writer 
= new XmlTextWriter(_fileXls, null);

            xslt.Transform(nav, 
null, writer, null);
            writer.Close();

            File.Delete(_fileXml);

            flag 
= true;
        }

        
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
string msg = ex.Message;
            
throw;
        }

        
return flag;
    }


    
public bool BuildExcelWithSheets(DataSet ds, string tempPath, string xslPath)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
bool flag = false;

        
if (File.Exists(tempPath))
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            File.Delete(tempPath);
        }

        
string _path = tempPath.Substring(0, tempPath.Length - 4);
        
string _fileXml = _path + ".xml";
        
string _fileXsl = _path + ".xsl";
        
string _fileXls = _path + ".xls";
        
string _fileXsd = _path + ".xsd";

        
try
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            GetXmlFile(ds, _fileXml);

            XmlDocument doc 
= new XmlDocument();
            doc.Load(_fileXml);

            XslTransform xslt 
= new XslTransform();
            xslt.Load(xslPath);

            XmlElement root 
= doc.DocumentElement;
            XPathNavigator nav 
= root.CreateNavigator();
            XmlTextWriter writer 
= new XmlTextWriter(_fileXsd, null);

            xslt.Transform(nav, 
null, writer, null);
            writer.Close();

            File.Delete(_fileXml);

            StreamReader rd 
= new StreamReader(_fileXsd, Encoding.UTF8);
            
string ss = rd.ReadToEnd();
            ss 
= ss.Replace("&lt;""<");
            ss 
= ss.Replace("&gt;"">");
            rd.Close();

            StreamWriter sw 
= new StreamWriter(_fileXls);
            sw.Write(ss);

            File.Delete(_fileXsd);
            sw.Close();

            flag 
= true;
        }

        
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
string msg = ex.Message;
            
throw;
        }


        
return flag;
    }

}

4、XSLT(demo.xsl)
ContractedBlock.gif ExpandedBlockStart.gif Code
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl
="http://www.w3.org/1999/XSL/Transform">
 
<xsl:template match="/">
  
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
   xmlns:o
="urn:schemas-microsoft-com:office:office"
   xmlns:x
="urn:schemas-microsoft-com:office:excel"
   xmlns:ss
="urn:schemas-microsoft-com:office:spreadsheet"
   xmlns:html
="http://www.w3.org/TR/REC-html40">

   
<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
    
<ActiveSheet>1</ActiveSheet>
    
<ProtectStructure>False</ProtectStructure>
    
<ProtectWindows>False</ProtectWindows>
   
</ExcelWorkbook>
   
<Styles>
    
<Style ss:ID="Default" ss:Name="Normal">
     
<Alignment ss:Vertical="Center"/>
     
<Borders/>
     
<Font ss:FontName="Arial" x:CharSet="134" ss:Size="11" ss:Color="#000000"/>
     
<Interior/>
     
<NumberFormat/>
     
<Protection/>
    
</Style>
    
<Style ss:ID="s67">
     
<Alignment ss:Horizontal="Left" ss:Vertical="Center" ss:Indent="1"/>
     
<Font ss:FontName="Arial" x:CharSet="134" ss:Size="11" ss:Color="#000000"
      ss:Bold
="1"/>
     
<NumberFormat ss:Format="@"/>
    
</Style>
    
<Style ss:ID="s68">
     
<Alignment ss:Horizontal="Left" ss:Vertical="Center" ss:Indent="1"/>
     
<NumberFormat ss:Format="@"/>
    
</Style>
   
</Styles>
   
<Worksheet ss:Name="employee">
    
<Table ss:ExpandedColumnCount="2"  x:FullColumns="1"
     x:FullRows
="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="13.5">
     
<Column ss:StyleID="s68" ss:Width="85.5"/>
     
<Column ss:StyleID="s68" ss:Width="99"/>
     
<Row>
      
<Cell ss:StyleID="s67">
       
<Data ss:Type="String">employeeId</Data>
      
</Cell>
      
<Cell ss:StyleID="s67">
       
<Data ss:Type="String">title</Data>
      
</Cell>
     
</Row>
     
<xsl:for-each select="NewDataSet/Table">
      
<Row>
       
<Cell>
        
<Data ss:Type="String">
         
<xsl:value-of select="employeeId" />
        
</Data>
       
</Cell>
       
<Cell>
        
<Data ss:Type="String">
         
<xsl:value-of select="title" />
        
</Data>
       
</Cell>
      
</Row>
     
</xsl:for-each>

    
</Table>
    
<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
     
<PageSetup>
      
<Header x:Margin="0.3"/>
      
<Footer x:Margin="0.3"/>
      
<PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/>
     
</PageSetup>

     
<ProtectObjects>False</ProtectObjects>
     
<ProtectScenarios>False</ProtectScenarios>
    
</WorksheetOptions>
   
</Worksheet>
   
<Worksheet ss:Name="sale">
    
<Table ss:ExpandedColumnCount="2"  x:FullColumns="1"
     x:FullRows
="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="13.5">
     
<Column ss:StyleID="s68" ss:Width="85.5"/>
     
<Column ss:StyleID="s68" ss:Width="99"/>
     
<Row>
      
<Cell ss:StyleID="s67">
       
<Data ss:Type="String">productId</Data>
      
</Cell>
      
<Cell ss:StyleID="s67">
       
<Data ss:Type="String">productName</Data>
      
</Cell>
     
</Row>
     
<xsl:for-each select="NewDataSet/Table1">
      
<Row>
       
<Cell>
        
<Data ss:Type="String">
         
<xsl:value-of select="productId" />
        
</Data>
       
</Cell>
       
<Cell>
        
<Data ss:Type="String">
         
<xsl:value-of select="productName" />
        
</Data>
       
</Cell>
      
</Row>
     
</xsl:for-each>

    
</Table>
    
<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
     
<PageSetup>
      
<Header x:Margin="0.3"/>
      
<Footer x:Margin="0.3"/>
      
<PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/>
     
</PageSetup>

     
<ProtectObjects>False</ProtectObjects>
     
<ProtectScenarios>False</ProtectScenarios>
    
</WorksheetOptions>
   
</Worksheet>
  
</Workbook>
 
</xsl:template>
</xsl:stylesheet>

转载于:https://www.cnblogs.com/aspsmile/archive/2008/08/05/971478.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值