zoukankan
html css js c++ java
XML结合XSLT生成Excel(导入到多个Worksheet)
1、.aspx
Code
<%
@ 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
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
{
protected
void
Page_Load(
object
sender, EventArgs e)
{
}
protected
void
btnExport_Click(
object
sender, EventArgs e)
{
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))
{
rewrite(objectPath);
DownLoad(Page.Response, objectPath, fileName
+
"
.xls
"
);
}
}
private
void
DownLoad(System.Web.HttpResponse response,
string
filepath,
string
VirtualName)
{
try
{
if
(File.Exists(filepath))
{
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)
{
}
finally
{
if
(File.Exists(filepath))
{
File.Delete(filepath);
}
}
}
private
void
rewrite(
string
objectPath)
{
try
{
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)
{
Response.Write(ex.Message);
}
finally
{
}
}
}
3、ExcelBuilder
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
{
public
ExcelBuilder()
{
}
private
void
GetXSLFile(DataSet ds,
string
XslPath,
params
string
[] Titles)
{
string
strColumn
=
""
;
string
strRow
=
""
;
string
dsName
=
ds.DataSetName;
string
tableName
=
ds.Tables[
0
].TableName;
string
header
=
dsName
+
"
/
"
+
tableName;
foreach
(
string
title
in
Titles)
{
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))
{
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)
{
if
(File.Exists(XmlFilePath))
{
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)
{
bool
flag
=
false
;
if
(File.Exists(tempPath))
{
File.Delete(tempPath);
}
string
_path
=
tempPath.Substring(
0
, tempPath.Length
-
4
);
string
_fileXml
=
_path
+
"
.xml
"
;
string
_fileXsl
=
_path
+
"
.xsl
"
;
string
_fileXls
=
_path
+
"
.xls
"
;
try
{
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)
{
string
msg
=
ex.Message;
throw
;
}
return
flag;
}
public
bool
BuildExcelWithSheets(DataSet ds,
string
tempPath,
string
xslPath)
{
bool
flag
=
false
;
if
(File.Exists(tempPath))
{
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
{
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(
"
<
"
,
"
<
"
);
ss
=
ss.Replace(
"
>
"
,
"
>
"
);
rd.Close();
StreamWriter sw
=
new
StreamWriter(_fileXls);
sw.Write(ss);
File.Delete(_fileXsd);
sw.Close();
flag
=
true
;
}
catch
(Exception ex)
{
string
msg
=
ex.Message;
throw
;
}
return
flag;
}
}
4、XSLT(demo.xsl)
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
>
查看全文
相关阅读:
6.1.1.1 属性类型之数据属性
6.1 理解对象
5.7.2.4 random() 方法
5.7.2.3 舍入方法
5.7.2.2 min()和max()方法
5.7.2.1 Math对象
5.7.1.4 window对象
frontend2_s9_part2_fe_d48_form
s10_part3_django_basic.md
frontend1_s9_part2_d47_html
原文地址:https://www.cnblogs.com/aspsmile/p/971478.html
最新文章
Nginx工作原理和优化、漏洞
Nginx和PHP-FPM的启动、重启、停止脚本分享
mysql删除重复记录,保存Id最小的一条
在windows上部署使用Redis
MongoDB常用操作命令大全
PHP操作Mongodb之增删改查篇
PHP操作Mongodb之高级查询篇
Shell编程
AJAX原理
数据库缓存层的优化
热门文章
动态语言静态化
wed资源防盗链
减少HTTP请求
浏览器缓存和压缩优化技术
高并发、大流量解决方案
常见的HTTP错误码
php解析、封装JSON与XML
6.1.3 读取属性的特性
6.1.2 定义多个属性
6.1.1.2 属性类型之访问器属性
Copyright © 2011-2022 走看看