js导入导出excel(实例代码)


Posted in Javascript onNovember 25, 2013

导入:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
     <title>Untitled Page</title>
</head>
<script language="javascript" type="text/javascript">
function importXLS(fileName)
{  
     objCon = new ActiveXObject("ADODB.Connection");
     objCon.Provider = "Microsoft.Jet.OLEDB.4.0";
     objCon.ConnectionString = "Data Source=" + fileName + ";Extended Properties=Excel 8.0;";
     objCon.CursorLocation = 1;
     objCon.Open;
     var strQuery;
     //Get the SheetName
     var strSheetName = "Sheet1$";
     var rsTemp =   new ActiveXObject("ADODB.Recordset");
     rsTemp = objCon.OpenSchema(20);
     if(!rsTemp.EOF)
     strSheetName = rsTemp.Fields("Table_Name").Value;
     rsTemp = null;
     rsExcel =   new ActiveXObject("ADODB.Recordset");
     strQuery = "SELECT * FROM [" + strSheetName + "]";
     rsExcel.ActiveConnection = objCon;
     rsExcel.Open(strQuery);
     while(!rsExcel.EOF)
     {
     for(i = 0;i<rsExcel.Fields.Count;++i)
     {
     alert(rsExcel.Fields(i).value);
     }
     rsExcel.MoveNext; 
     }
     // Close the connection and dispose the file
     objCon.Close;
     objCon =null;
     rsExcel = null;
}
</script>
</head>
<body>
<input type="file" id="f" />
<input type="button" id="b" value="import" onclick="if(f.value=='')alert('请选择xls文件');else importXLS(f.value)" />
</body>
</html>

导出:
function AutomateExcel()
{

// Start Excel and get Application object.
var oXL = new ActiveXObject("Excel.Application");


oXL.Visible = true;


// Get a new workbook.
var oWB = oXL.Workbooks.Add();
var oSheet = oWB.ActiveSheet;


// Add table headers going cell by cell.
oSheet.Cells(1, 1).Value = "First Name";
oSheet.Cells(1, 2).Value = "Last Name";
oSheet.Cells(1, 3).Value = "Full Name";
oSheet.Cells(1, 4).Value = "Salary";


// Format A1:D1 as bold, vertical alignment = center.
oSheet.Range("A1", "D1").Font.Bold = true;
oSheet.Range("A1", "D1").VerticalAlignment = -4108; //xlVAlignCenter


// Create an array to set multiple values at once.


// Fill A2:B6 with an array of values (from VBScript).
oSheet.Range("A2", "B6").Value = CreateNamesArray();


// Fill C2:C6 with a relative formula (=A2 & " " & B2).
var oRng = oSheet.Range("C2", "C6");
oRng.Formula = "=A2 & " " & B2";


// Fill D2:D6 with a formula(=RAND()*100000) and apply format.
oRng = oSheet.Range("D2", "D6");
oRng.Formula = "=RAND()*100000";
oRng.NumberFormat = "$0.00";


// AutoFit columns A:D.
oRng = oSheet.Range("A1", "D1");
oRng.EntireColumn.AutoFit();


// Manipulate a variable number of columns for Quarterly Sales Data.
DispalyQuarterlySales(oSheet);


// Make sure Excel is visible and give the user control
// of Excel's lifetime.
oXL.Visible = true;
oXL.UserControl = true;
}<HTML>
<HEAD>
<TITLE>将页面中指定表格的数据导入到Excel中</TITLE>
<SCRIPT LANGUAGE="javascript">
<!--
function AutomateExcel()
{


var oXL = new ActiveXObject("Excel.Application"); //创建应该对象
var oWB = oXL.Workbooks.Add();//新建一个Excel工作簿
var oSheet = oWB.ActiveSheet;//指定要写入内容的工作表为活动工作表
var table = document.all.data;//指定要写入的数据源的id
var hang = table.rows.length;//取数据源行数
var lie = table.rows(0).cells.length;//取数据源列数


// Add table headers going cell by cell.
for (i=0;i<hang;i++){//在Excel中写行
for (j=0;j<lie;j++){//在Excel中写列
//定义格式
oSheet.Cells(i+1,j+1).NumberFormatLocal = "@";
//!!!!!!!上面这一句是将单元格的格式定义为文本
oSheet.Cells(i+1,j+1).Font.Bold = true;//加粗
oSheet.Cells(i+1,j+1).Font.Size = 10;//字体大小
oSheet.Cells(i+1,j+1).value = table.rows(i).cells(j).innerText;//向单元格写入值
}
}
oXL.Visible = true;
oXL.UserControl = true;
}
//-->
</SCRIPT>
</HEAD>


<BODY>
<table border="0" width="300" id="data" bgcolor="black" cellspacing="1">
<tr bgcolor="white">
<td>编号</td>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
</tr>
<tr bgcolor="white">
<td>0001</td>
<td>张三</td>
<td>22</td>
<td>女</td>
</tr>
<tr bgcolor="white">
<td>0002</td>
<td>李四</td>
<td>23</td>
<td>男</td>
</tr>
</table>
<input type="button" name="out_excel" onclick="AutomateExcel();" value="导出到excel">
</BODY>
</HTML>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<!-- 导出excle的三个方法 要把ie浏览器的"对没有标记为安全的 ActiveX 控件进行初始化和脚本运行 设置为提示或启用" --> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 
    <title>WEB页面导出为EXCEL文档的方法</title> 
</head> 
<body> 
    <table id="tableExcel" width="100%" border="1" cellspacing="0" cellpadding="0"> 
        <tr> 
            <td colspan="5" align="center"> 
                WEB页面导出为EXCEL文档的方法 
            </td> 
        </tr> 
        <tr> 
            <td> 
                列标题1 
            </td> 
            <td> 
                列标题2 
            </td> 
            <td> 
                列标题3 
            </td> 
            <td> 
                列标题4 
            </td> 
            <td> 
                列标题5 
            </td> 
        </tr> 
        <tr> 
            <td> 
                aaa 
            </td> 
            <td>             </td> 
            <td> 
                ccc 
            </td> 
            <td> 
                ddd 
            </td> 
            <td> 
                eee 
            </td> 
        </tr> 
        <tr> 
            <td> 
                AAA 
            </td> 
            <td> 
            </td> 
            <td> 
                CCC 
            </td> 
            <td> 
                DDD 
            </td> 
            <td> 
                EEE 
            </td> 
        </tr> 
        <tr> 
            <td> 
                FFF 
            </td> 
            <td> 
                GGG 
            </td> 
            <td> 
                HHH 
            </td> 
            <td> 
                III 
            </td> 
            <td> 
                JJJ 
            </td> 
        </tr> 
    </table> 
    <input type="button" onclick="javascript:method1('tableExcel');" value="第一种方法导入到EXCEL"> 
    <input type="button" onclick="javascript:method2('tableExcel');" value="第二种方法导入到EXCEL"> 
    <input type="button" onclick="javascript:getXlsFromTbl('tableExcel',null);" value="第三种方法导入到EXCEL"> 

    <script language="javascript"> 
        function method1(tableid) {//整个表格拷贝到EXCEL中 
            var curTbl = document.getElementById(tableid); 
            var oXL = new ActiveXObject("Excel.Application"); //创建AX对象excel 
            var oWB = oXL.Workbooks.Add(); //获取workbook对象 
            var oSheet = oWB.ActiveSheet; //激活当前sheet 
            var sel = document.body.createTextRange(); 
            sel.moveToElementText(curTbl); //把表格中的内容移到TextRange中 
            sel.select(); //全选TextRange中内容 
            sel.execCommand("Copy"); //复制TextRange中内容 
            oSheet.Paste(); //粘贴到活动的EXCEL中 
            oXL.Visible = true; //设置excel可见属性 
        } 
        function method2(tableid) //读取表格中每个单元到EXCEL中 
        { 
            var curTbl = document.getElementById(tableid); 
            var oXL = new ActiveXObject("Excel.Application"); //创建AX对象excel 
            var oWB = oXL.Workbooks.Add(); //获取workbook对象 
            var oSheet = oWB.ActiveSheet; //激活当前sheet 
            var Lenr = curTbl.rows.length; //取得表格行数 
            for (i = 0; i < Lenr; i++) { 
                var Lenc = curTbl.rows(i).cells.length; //取得每行的列数 
                for (j = 0; j < Lenc; j++) { 
                    oSheet.Cells(i + 1, j + 1).value = curTbl.rows(i).cells(j).innerText; //赋值 
                } 
            } 
            oXL.Visible = true; //设置excel可见属性 
        } 
        function getXlsFromTbl(inTblId, inWindow) { 
            try { 
                var allStr = ""; 
                var curStr = ""; 
                if (inTblId != null && inTblId != "" && inTblId != "null") { 
                    curStr = getTblData(inTblId, inWindow); 
                } 
                if (curStr != null) { 
                    allStr += curStr; 
                } 
                else { 
                    alert("你要导出的表不存在!"); 
                    return; 
                } 
                var fileName = getExcelFileName(); 
                doFileExport(fileName, allStr); 
            } 
            catch (e) { 
                alert("导出发生异常:" + e.name + "->" + e.description + "!"); 
            } 
        } 
        function getTblData(inTbl, inWindow) { 
            var rows = 0; 
            var tblDocument = document; 
            if (!!inWindow && inWindow != "") { 
                if (!document.all(inWindow)) { 
                    return null; 
                } 
                else { 
                    tblDocument = eval(inWindow).document; 
                } 
            } 
            var curTbl = tblDocument.getElementById(inTbl); 
            var outStr = ""; 
            if (curTbl != null) { 
                for (var j = 0; j < curTbl.rows.length; j++) { 
                    for (var i = 0; i < curTbl.rows[j].cells.length; i++) { 
                        if (i == 0 && rows > 0) { 
                            outStr += " /t"; 
                            rows -= 1; 
                        } 
                        outStr += curTbl.rows[j].cells[i].innerText + "/t"; 
                        if (curTbl.rows[j].cells[i].colSpan > 1) { 
                            for (var k = 0; k < curTbl.rows[j].cells[i].colSpan - 1; k++) { 
                                outStr += " /t"; 
                            } 
                        } 
                        if (i == 0) { 
                            if (rows == 0 && curTbl.rows[j].cells[i].rowSpan > 1) { 
                                rows = curTbl.rows[j].cells[i].rowSpan - 1; 
                            } 
                        } 
                    } 
                    outStr += "/r/n"; 
                } 
            } 
            else { 
                outStr = null; 
                alert(inTbl + "不存在!"); 
            } 
            return outStr; 
        } 
        function getExcelFileName() { 
            var d = new Date(); 
            var curYear = d.getYear(); 
            var curMonth = "" + (d.getMonth() + 1); 
            var curDate = "" + d.getDate(); 
            var curHour = "" + d.getHours(); 
            var curMinute = "" + d.getMinutes(); 
            var curSecond = "" + d.getSeconds(); 
            if (curMonth.length == 1) { 
                curMonth = "0" + curMonth; 
            } 
            if (curDate.length == 1) { 
                curDate = "0" + curDate; 
            } 
            if (curHour.length == 1) { 
                curHour = "0" + curHour; 
            } 
            if (curMinute.length == 1) { 
                curMinute = "0" + curMinute; 
            } 
            if (curSecond.length == 1) { 
                curSecond = "0" + curSecond; 
            } 
            var fileName = "leo_zhang" + "_" + curYear + curMonth + curDate + "_" 
+ curHour + curMinute + curSecond + ".csv"; 
            return fileName; 
        } 
        function doFileExport(inName, inStr) { 
            var xlsWin = null; 
            if (!!document.all("glbHideFrm")) { 
                xlsWin = glbHideFrm; 
            } 
            else { 
                var width = 6; 
                var height = 4; 
                var openPara = "left=" + (window.screen.width / 2 - width / 2) 
   + ",top=" + (window.screen.height / 2 - height / 2) 
   + ",scrollbars=no,width=" + width + ",height=" + height; 
                xlsWin = window.open("", "_blank", openPara); 
            } 
            xlsWin.document.write(inStr); 
            xlsWin.document.close(); 
            xlsWin.document.execCommand('Saveas', true, inName); 
            xlsWin.close(); 
        } 
    </script> 
</body> 
</html>
Javascript 相关文章推荐
ExtJs 表单提交登陆实现代码
Aug 19 Javascript
jquery单选框radio绑定click事件实现方法
Jan 14 Javascript
最流行的Node.js精简型和全栈型开发框架介绍
Feb 26 Javascript
JS替换字符串中空格方法
Apr 17 Javascript
CKEditor无法验证的解决方案(js验证+jQuery Validate验证)
May 09 Javascript
JS获取input file绝对路径的方法(推荐)
Aug 02 Javascript
微信小程序 简单DEMO布局,逻辑,样式的练习
Nov 30 Javascript
canvas学习之API整理笔记(二)
Dec 29 Javascript
浅析Vue自定义组件的v-model
Nov 26 Javascript
Angularjs之ngModel中的值验证绑定方法
Sep 13 Javascript
vue项目中仿element-ui弹框效果的实例代码
Apr 22 Javascript
Vue通过WebSocket建立长连接的实现代码
Nov 05 Javascript
用javascript添加控件自定义属性解析
Nov 25 #Javascript
JavaScript/Js脚本处理html元素的自定义属性解析(亲测兼容Firefox与IE)
Nov 25 #Javascript
几种设置表单元素中文本输入框不可编辑的方法总结
Nov 25 #Javascript
js动态添加删除,后台取数据(示例代码)
Nov 25 #Javascript
javascript新建标签,判断键盘输入,以及判断焦点(示例代码)
Nov 25 #Javascript
jQuery中获取checkbox选中项等操作及注意事项
Nov 24 #Javascript
javascript 弹出的窗口返回值给父窗口具体实现
Nov 23 #Javascript
You might like
基于HTTP长连接的&quot;服务器推&quot;技术的php 简易聊天室
2009/10/31 PHP
linux下删除7天前日志的代码(php+shell)
2011/01/02 PHP
php中禁止单个IP与ip段访问的代码小结
2012/07/04 PHP
thinkPHP中create方法与令牌验证实例浅析
2015/12/08 PHP
php实现JWT(json web token)鉴权实例详解
2019/11/05 PHP
JavaScript 快捷键设置实现代码
2009/03/13 Javascript
js生成动态表格并为每个单元格添加单击事件的方法
2014/04/14 Javascript
Angularjs过滤器使用详解
2016/05/25 Javascript
checkbox 选中一个另一个checkbox也会选中的实现代码
2016/07/09 Javascript
JavaScript 计算笛卡尔积实例详解
2016/12/02 Javascript
canvas 实现中国象棋
2017/02/17 Javascript
jstree单选功能的实现方法
2017/06/07 Javascript
Vue-router 类似Vuex实现组件化开发的示例
2017/09/15 Javascript
vue-cli如何引入bootstrap工具的方法
2017/10/19 Javascript
JavaScript中变量、指针和引用功能与操作示例
2018/08/04 Javascript
微信小程序自定义tabBar组件开发详解
2020/09/24 Javascript
详解elementui之el-image-viewer(图片查看器)
2019/08/30 Javascript
JavaScript实现多个物体同时运动
2020/03/12 Javascript
使用JavaScript通过前端发送电子邮件
2020/05/22 Javascript
Vue.js暴露方法给WebView的使用操作
2020/09/07 Javascript
python实现的重启关机程序实例
2014/08/21 Python
python网络编程之读取网站根目录实例
2014/09/30 Python
python Pygame的具体使用讲解
2017/11/03 Python
解决pandas使用read_csv()读取文件遇到的问题
2018/06/15 Python
Django和Flask框架优缺点对比
2019/10/24 Python
Python带参数的装饰器运行原理解析
2020/06/09 Python
css3中检验表单的required,focus,valid和invalid样式
2014/02/21 HTML / CSS
HTML5 使用 sessionStorage 进行页面传值的方法
2018/07/02 HTML / CSS
美国波西米亚风格精品店:South Moon Under
2019/10/26 全球购物
JAVA软件工程师测试题
2014/07/25 面试题
建筑学推荐信
2013/11/03 职场文书
园林技术个人的自我评价
2014/01/08 职场文书
汽车专业求职信
2014/06/05 职场文书
2016师德师风学习心得体会
2016/01/12 职场文书
Python 如何安装Selenium
2021/05/06 Python
Win11安装受阻怎么办? Windows11安装问题与解决方案汇总
2021/11/21 数码科技