我正在从我的gridview导出excel表,我将其与虚拟数据绑定。我正在使用jquery mehod导出excel但它不起作用。我在jquery中有以下功能。
<script type="text/javascript">
function exportToExcel()
{
var oExcel = new ActiveXObject("Excel.Application");
var oBook = oExcel.Workbooks.Add;
var oSheet = oBook.Worksheets(1);
var detailsTable = document.getElementById('<%= gvSearchResult.ClientID %>');
alert(detailsTable);
for (var y=0;y<detailsTable.rows.length;y++)
// detailsTable is the table where the content to be exported is
{
for (var x=0;x<detailsTable.rows(y).cells.length;x++)
{
var cellData = detailsTable.rows(y).cells(x).innerText;
var cellHTML = detailsTable.rows(y).cells(x).innerHTML;
if (cellHTML.toLowerCase().indexOf("<table") == -1 && cellHTML.toLowerCase().indexOf("schedule") == -1) // check to omit page numbers
{
oSheet.Cells(y+1,x+1) = cellData;
}
}
}
oExcel.Visible = true;
oExcel.UserControl = true;
}
我使用上面的功能。我点击了一个按钮我要导出Excel工作表。按钮如下:
<asp:Button runat="server" ID="btnClickXport" Text="Xport2Xcel" OnClientClick="exportToExcel()" />
它不起作用。我测试实际上新的ActiveXobject(“Excel.Application”);在开始导致问题。我需要做什么?
答案 0 :(得分:1)
我使用这个jquery插件将html表导出到csv: https://code.google.com/p/jqtable2csv/
使用示例:
$("#my-table").table2csv({
callback: function (csv, name) {
jQuery.post(
url, encodeURIComponent(csv),
function (data) {
location.href = "/file?csv=" + csv + "&name=" + name;
}
);
});
话虽如此......如果您使用的是ASP.Net,您可能需要处理此服务器端,因为javascript在旧版浏览器上启动下载存在一些挑战。
答案 1 :(得分:0)
您可以尝试以下代码将datagridview
导出为Excel:
protected void ExportResultToExcel(string fileName)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
gvSearchResult.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}