前端生成的html表格经常需要导出到excel中,利用JS和Office控件可以做到,但仅限于IE,还要启用安全设置。
想找一个简单的办法将HTML内容直接转换成Excel文件,如果直接修改网页头信息输出,虽然可以导出,但打开时会提示格式不是Excel的,怎样才能导出真正的Excel文件?
aspose.cells是个功能强大的控件,可以方便的生成excel文件。经考虑,将html发送到后台,保存为xls文件(其实是html内容),再用aspose.cells打开,输出到客户端,这样就变成了真正的excel文件了。
基本代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="htmlTableToExcel.aspx.cs" Inherits="ASPOSE_htmlTableToExcel" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<input id="Button1" type="button" value="button" οnclick="toExcel()" />
<div>
<table style="width: 200px; border:1px red solid;" id="table1">
<tr>
<td style="width:30px;">2</td>
<td style="width:80px;">ddsf</td>
<td style="width:90px;">s</td>
</tr>
<tr>
<td>3</td>
<td style="color:red; border:2px green solid;">sfas</td>
<td>f</td>
</tr>
<tr>
<td>5</td>
<td>ggg</td>
<td>g</td>
</tr>
<tr>
<td> </td>
<td rowspan="2">fffg</td>
<td> </td>
</tr>
<tr>
<td>z</td>
<td>f</td>
</tr>
</table>
</div>
</form>
</body>
</html>
<script src="../JS/Jquery-1.8.2.min.js"></script>
<script type="text/javascript">
function toExcel() {
if (!document.getElementById('div_div_div_1234567890')) {
$('body').append("<div id='div_div_div_1234567890' style='display:none;'>"
+ "<iframe id='submitFrame' name='submitFrame'></iframe>"
+ "<form id='form_form_form_1234567890' method='post' target='submitFrame' οnsubmit='return false;'>"
+ "<input type='hidden' id='input_input_input_1234567890' name='table' />"
+ "</form>"
+ "</div>");
}
document.getElementById('input_input_input_1234567890').value = document.getElementById('table1').outerHTML;
document.getElementById('form_form_form_1234567890').action = "htmlTableToExcel.ashx"
document.getElementById('form_form_form_1234567890').submit();
}
</script>
htmlTableToExcel.ashx:
<%@ WebHandler Language="C#" Class="htmlTableToExcel" %>
using System;
using System.Web;
using Aspose.Cells;
using System.IO;
using System.Text;
public class htmlTableToExcel : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string table = context.Request["table"];
//test info
if (table == null || table == "")
{
table = @"<table style='width: 200px' id='table1'>
<tr>
<td style='width:30px;'>abc</td>
<td style='width:80px;'>123</td>
<td style='width:90px;'>这是测试信息</td>
</tr>
</table>";
}
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter( stream );
writer.Write( table );
writer.Flush();
//加载选项,html,否则会出错
LoadOptions lo = new LoadOptions(LoadFormat.Html);
Workbook wb = new Workbook(stream, lo);
//输出到浏览器
wb.Save(context.Response, "output.xls", ContentDisposition.Attachment, new XlsSaveOptions(SaveFormat.Excel97To2003));
}
public bool IsReusable
{
get
{
return false;
}
}
}
以上为简单的测试代码,经检验可以生成excel文件,只是格式方面像边框、宽度什么的就没有了,合并单元格什么的能保留;要是要求不高就将就用着吧。