將表格資料匯入Excel表程式碼例項

antzone發表於2017-03-17

表格可以用來組織資料,但是Excel的功能更為強大,在辦公中幾乎是比不可少的,所以有時候可能需要將表格中的資料匯入到Excel表中,這樣更加容易管理和儲存,下面就是一段實現此功能的程式碼例項。

程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script type="text/javascript"> 
var idTmr=""; 
function killExcelProcess(appExcel_){ 
  appExcel_.Quit(); 
  appExcel_ = null; 
  idTmr = window.setInterval("Cleanup();",1); 
} 
 
function exportToExcel(tableid,notitleandsearch){ 
  try { 
    clipboardData.setData('Text',''); 
    var appExcel = new ActiveXObject("Excel.Application"); 
    killExcelProcess(appExcel); 
    appExcel.workbooks.add; 
 
    if (notitleandsearch==null||notitleandsearch==false){ 
      var elTable = document.getElementById('div_title'); 
      var oRangeRef = document.body.createTextRange(); 
      oRangeRef.moveToElementText(elTable); 
      oRangeRef.execCommand( "Copy" ); 
      appExcel.ActiveSheet.Cells(1,3).select(); 
      appExcel.ActiveSheet.Paste(); 
 
      clipboardData.setData('Text',''); 
      appExcel.ActiveSheet.Cells(2,1).select(); 
      appExcel.ActiveSheet.Paste(); 
    } 
 
    var elTable1 = document.getElementById(tableid); 
    var oRangeRef1 = document.body.createTextRange(); 
    oRangeRef1.moveToElementText(elTable1); 
    oRangeRef1.execCommand( "Copy" ); 
 
    appExcel.WorkSheets(1).Activate; 
    if (notitleandsearch==null||notitleandsearch==false){ 
      appExcel.ActiveSheet.Cells(3,1).select(); 
    }else{ 
      appExcel.ActiveSheet.Cells(1,1).select(); 
    } 
    appExcel.WorkSheets(1).Activate; 
    appExcel.ActiveSheet.Paste(); 
    appExcel.Visible = true; 
  } 
  catch(e) { 
    alert("請確認IE安全設定,ActiveX都啟用!"); 
    return false; 
  } 
  clipboardData.setData('text',''); 
} 
</script>
</HEAD>
 
<BODY>
<button>匯出</button>
<br>
<div id='div_title' ><font color='black' size='4'><strong>匯出報表</strong></font></div>
<table id = "testList" bordercolor="#000000" border = "1">
  <tr>
    <td>螞蟻部落一</td>
    <td>螞蟻部落二</td>
    <td>螞蟻部落三</td>
  </tr>
  <tr>
    <td>螞蟻部落一</td>
    <td>螞蟻部落二</td>
    <td>螞蟻部落三</td>
  </tr>
  <tr>
    <td>螞蟻部落一</td>
    <td>螞蟻部落二</td>
    <td>螞蟻部落三</td>
  </tr>
  <tr>
    <td>螞蟻部落一</td>
    <td>螞蟻部落二</td>
    <td>螞蟻部落三</td>
  </tr>
  <tr>
    <td>螞蟻部落一</td>
    <td>螞蟻部落二</td>
    <td>螞蟻部落三</td>
  </tr>
  <tr>
    <td>螞蟻部落一</td>
    <td>螞蟻部落二</td>
    <td>螞蟻部落三</td>
  </tr>
  <tr>
    <td colspan="2">總計:</td>
    <td>10</td>
  </tr>
</table>
</body>
</html>

相關文章