JavaScript將頁面表格匯出為Excel的具體實現_javascript技巧

來源:互聯網
上載者:User
複製代碼 代碼如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>匯出Excel</TITLE>
<script type="text/javascript">
var idTmr = "";
function killExcelProcess(appExcel_){
appExcel_.Quit();
appExcel_ = null;
idTmr = window.setInterval("Cleanup();",1);
}

//匯出到excel,參數tableid為JSP頁面需要匯出的table的id,需要更改IE的安全設定,ActiveX都開啟,如果還是不能使用,再服務端運行“regsvr32 scrrun.dll”
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 onclick="javascript:exportToExcel('testList','');">匯出</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>1</td>
<td>張三1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>張三2</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>張三3</td>
<td>2</td>
</tr>
<tr>
<td>4</td>
<td>張三4</td>
<td>2</td>
</tr>
<tr>
<td>5</td>
<td>張三5</td>
<td>2</td>
</tr>
<tr>
<td colspan="2">總計:</td>
<td>10</td>
</tr>

</table>
</BODY>
</HTML>
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.