1、Html导出Excel的方法:
1.1、前台代码:
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<html xmlns="http://www.w3.org/1999/xhtml"><head></head><meta http-equiv="content-type" content="text/html; charset=UTF-8" /><body>
<style type="text/css">
.ExportTable
{
border-top:.1pt solid #000000;
border-right:.1pt solid #000000;
border-left:.1pt solid #000000;
border-bottom:.1pt solid #000000;
margin-top:1px;
margin-left:1px;
}
.ExportTableTd1
{
border-top:none;
border-right:.1pt solid #000000;
border-left:none;
border-bottom:.1pt solid #000000;
text-align:left;
height:20px;
color:#000000;
font-size:10pt;
}
.ExportTableTd2
{
border-top:none;
border-right:.1pt solid #000000;
border-left:none;
border-bottom:.1pt solid #000000;
text-align:left;
height:20px;
font-size:10pt;
background-color:#8fb3f3;
}
.ExportTableTh
{
border-top:none;
border-right:.1pt solid #000000;
border-left:none;
border-bottom:.1pt solid #000000;
text-align:center;
font-size:12pt;
background-color:#6998EF;
color:#FFFFFF;
text-align:left;
}
</style>
<table cellpadding="3" cellspacing="0" border="0" width="100%" class="ExportTable">
<tr>
<th class="ExportTableTh">NO.</th>
<th class="ExportTableTh">車間</th>
<th class="ExportTableTh">卡號</th>
<th class="ExportTableTh">工號</th>
<th class="ExportTableTh">姓名</th>
<th class="ExportTableTh">時間</th>
<th class="ExportTableTh">Memo</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td id="Td1" class="ExportTableTd1" runat="server"><%# Container.ItemIndex + 1%> </td>
<td id="Td2" class="ExportTableTd1" runat="server"><%#Eval("AreaName")%></td>
<td id="Td3" class="ExportTableTd1" runat="server"><%#Eval("CardNo")%> </td>
<td id="Td4" class="ExportTableTd1" runat="server"><%#Eval("WorkNo")%> </td>
<td id="Td5" class="ExportTableTd1" runat="server"><%#Eval("PersonName")%></td>
<td id="Td6" class="ExportTableTd1" runat="server"><%#Eval("LogTime")%> </td>
<td id="Td7" class="ExportTableTd1" runat="server"><%#Eval("logContent")%> </td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table></body></html>
</FooterTemplate>
</asp:Repeater>
2.2、后台代码
Response.ContentEncoding = System.Text.Encoding.UTF8;//注意编码
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8).ToString());
Response.ContentType = "application/ms-excel";
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
this.Repeater1.RenderControl(hw);
string outputStr = tw.ToString();
Response.Write(outputStr);
tw.Close();
Response.End();
总结:有时候Repeater里要定义一个完整的HTML语言导出才不会乱码,否则不管后台设置什么编码方式都乱码。(有时候不家完整的<html><head></head><body></body></html>也可以。)
优点:速度很快,几乎不耗什么系统资源,缺点:不是真正的Excel,有写Excel的功能不能用。