Welcome

首页 / 脚本样式 / JavaScript / JavaScript将Html中的Table表格导出为Excel的方法

JavaScript将Html中的Table表格导出为Excel的方法

function toExcel(){
    //window.location.href='<%=basePath%>pmb/excelShowInfo.do';
    //获取表格
    var exportFileContent = document.getElementById("datatable").outerHTML;
    //设置格式为Excel,表格内容通过btoa转化为base64,此方法只在文件较小时使用(小于1M)
    //exportFileContent=window.btoa(unescape(encodeURIComponent(exportFileContent)));
    //var link = "data:"+MIMEType+";base64," + exportFileContent;
    //使用Blob
    var blob = new Blob([exportFileContent], {type: "text/plain;charset=utf-8"});     	//解决中文乱码问题
    blob =  new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type});
    //设置链接
    var link = window.URL.createObjectURL(blob);
    var a = document.createElement("a");    //创建a标签
    a.download = "监测网址列表.xls";  //设置被下载的超链接目标(文件名)
    a.href = link;                            //设置a标签的链接
    document.body.appendChild(a);            //a标签添加到页面
    a.click();                                //设置a标签触发单击事件
    document.body.removeChild(a);            //移除a标签
}
以上方法可以用作快速导出,但不同的Office版本导出时打开可能会有警告提示。