Somsone建议我使用此功能将我的数据表导出到Excel,但它导出的HTML不仅仅是表格中的数据。如何才能导出数据和格式(宽度,颜色......)?
<!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>
<script>
function ExportHTMLTableToExcel()
{
var thisTable = document.getElementById("table").innerHTML;
window.clipboardData.setData("Text", thisTable);
var objExcel = new ActiveXObject ("Excel.Application");
objExcel.visible = true;
var objWorkbook = objExcel.Workbooks.Add;
var objWorksheet = objWorkbook.Worksheets(1);
objWorksheet.Paste;
alert('test');
}
</script>
<title>Java Friends</title>
</head>
<body>
<table id="table" style="font-weight: bold">
<tr style="background-color:red"><td>a</td><td>b</td></tr>
<tr><td>1</td><td>2</td></tr>
<tr>
<td colspan="2">
<button onclick="ExportHTMLTableToExcel()">
Get as Excel spreadsheet
</button>
</td>
</tr>
</table>
</body>
</html>
注意:如果安全选项download unsigned activex control
和download signed activex control
设置为“启用”,则此功能仅适用于IE
答案 0 :(得分:1)
请使用此代码,它对我来说很好
public void ExportToSpreadsheet(DataTable table, string name)
{
try
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.ClearHeaders();
String sr = string.Empty;
sr += "<html><body><table>";
sr += "<tr style=\"background-color:gray;color:white;\">";
foreach (DataColumn column in table.Columns)
{
sr += "<th>";
sr += column.ColumnName;
sr += "</th>";
}
sr += "</tr>";
sr += Environment.NewLine;
foreach (DataRow row in table.Rows)
{
sr += "<tr>";
for (int i = 0; i < table.Columns.Count; i++)
{
sr += "<td>";
sr += row.ItemArray[i];
sr += "</td>";
}
sr += "</tr>";
sr += Environment.NewLine;
}
sr += "</table></body></html>";
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + name + ".xls");
context.Response.Write(sr);
context.Response.Flush();
context.Response.End();
context.Response.Close();
}
catch (Exception ex)
{
}
}
希望得到这个帮助。
答案 1 :(得分:0)
jQuery DataTables TableTools插件可以让您轻松地将HTML表格导出到Excel,但它不会处理格式化。
您可以在此处查看运行插件的示例:http://www.datatables.net/extras/tabletools/
它可能无法处理格式化,但确实可以轻松导出HTML表格。
如果绝对需要格式化,那么您需要考虑将数据发送回服务器,然后让服务器将HTML处理到Excel中。如果您使用的是ASP.net,那么实际上很容易做到。