js实现HTML Table 导出为Excel格式(含合并列格式)

function PageToExcel(TableID,FirstRow,LastRowColor,SaveAsName){ 
this.lastRowColor=LastRowColor==""?0:LastRowColor; 
var today=new Date(); 
this.saveAsName=(SaveAsName==""?today.getYear()+""+(today.getMonth()+1) + today.getDate() + today.getHours() + today.getMinutes() + today.getSeconds()  + ".xls":SaveAsName); 
this.tableId=TableID; 
this.table=document.getElementById(this.tableId);//导出的table 对象 
this.rows=this.table.rows.length;//导出的table总行数 
this.colSumCols=this.table.rows(0).cells.length;//第一行总列数 
this.fromrow=FirstRow; 
this.beginCol=0; //起始列数 
this.cols=this.colSumCols; 
this.oXL=null; 
this.oWB=null; 
this.oSheet=null; 
this.rowSpans=1; //行合并 
this.colSpans=1; //列合并 
this.colsName={0:"A",1:"B", 2:"C", 3:"D", 4:"E", 5:"F", 6:"G", 7:"H", 8:"I",9:"J", 10:"K", 11:"L", 12:"M", 13:"N", 14:"O", 15:"P", 16:"Q", 16:"R" ,18:"S", 19:"T", 20:"U", 21:"V", 22:"W", 23:"X", 24:"Y", 25:"Z"}; 

} 
PageToExcel.prototype.DeleteExcelCols=function(NotShowColList){//数组NotShowColList 
    //this.notShowColList=NotShowColList;//不显示列集合,1,2,3,1 
    //删除excel中的列 
   var m=0; 
   for(var i=0;i<NotShowColList.length;i++){ 
   if(i>0){ 
m++; 
} 
var temp=NotShowColList[i]- m; 
var index=this.colsName[temp]; 
this.oSheet.Columns(index).Delete;//删除 
   } 
   m=0; 
} 
PageToExcel.prototype.CreateExcel=function(ExcelVisible){ 
   try{ 
   this.oXL = new ActiveXObject("Excel.Application"); //创建应该对象 
   this.oXL.Visible = ExcelVisible; 
   this.oWB = this.oXL.Workbooks.Add();//新建一个Excel工作簿 
   this.oSheet = this.oWB.ActiveSheet;//指定要写入内容的工作表为活动工作表 
   //不显示网格线 
   //this.oXL.ActiveWindow.DisplayGridlines=false; 
   }catch(e){ 
alert("请确认安装了非绿色版本的excel!"+e.description); 
CloseExcel(); 
   } 
} 
//关闭excel 
PageToExcel.prototype.CloseExcel=function(){ 
    this.oXL.DisplayAlerts = false;   
this.oXL.Quit();   
this.oXL = null;   
this.oWB=null;   
this.oSheet=null; 
} 

PageToExcel.prototype.ChangeElementToLabel=function (ElementObj){ 

   var GetText=""; 
   try{ 
   var childres=ElementObj.childNodes; 
  
   }catch(e){ return GetText} 
   if(childres.length<=0) return GetText; 
   for(var i=0;i<childres.length;i++){ 
   try{if(childres[i].style.display=="none"||childres[i].type.toLowerCase()=="hidden"){continue;}} 
   catch(e){} 
    
     try{ 
      switch (childres[i].nodeName.toLowerCase()){ 
        case "#text" : 
         GetText +=childres[i].nodeValue ; 
         break; 
        case "br" : 
         GetText +="\n"; 
         break; 
        case "img" : 
         GetText +=""; 
         break; 
        case "select" : 
         GetText +=childres[i].options[childres[i].selectedIndex].innerText ; 
         break; 
        case "input" : 
         if(childres[i].type.toLowerCase()=="submit"||childres[i].type.toLowerCase()=="button"){ 
          GetText +=""; 
         }else if(childres[i].type.toLowerCase()=="textarea"){ 
          GetText +=childres[i].innerText; 
         }else{ 
          GetText +=childres[i].value; 
         } 
         break; 
        default : 
         GetText += this.ChangeElementToLabel(childres[i]); 
         break; 
      } 
     
     }catch(e){} 
   } 
   return GetText; 
} 

PageToExcel.prototype.SaveAs=function (){ 
   //保存 
   try{ 
this.oXL.Visible =true; 
this.oXL.Application.OpenFile(this.saveAsName);
//var fname = this.oXL.Application.GetSaveAsFilename(this.saveAsName, "Excel Spreadsheets (*.xls), *.xls"); 
/*if(fname){ 
this.oWB.SaveAs(fname); 
this.oXL.Visible =false; 
} */
   }catch(e){}; 
} 
PageToExcel.prototype.Exec=function() 
{ 
  
   //寻找列数,考虑到第一行可能存在 
   for (var i=0; i<this.colSumCols;i++) { 
    var tmpcolspan = this.table.rows(0).cells(i).colSpan; 
    if ( tmpcolspan>1 ) { 
     this.cols += tmpcolspan-1; 
    } 
   } 
  
   //定义2维容器数据,1:行;2:列;值(0 可以填充,1 已被填充) 
   var container=new Array(this.rows); 
   for (var i=0;i<this.rows;i++) { 
    container[i]=new Array(this.cols); 
    for (j=0;j<this.cols;j++) { 
     container[i][j]=0; 
    } 
   } 
  
   //将所有单元置为文本,避免非数字列被自动变成科学计数法和丢失前缀的0 
   this.oSheet.Range(this.oSheet.Cells(this.fromrow+1,1), this.oSheet.Cells(this.fromrow+this.rows,this.cols)).NumberFormat = "@"; 
   // 循环行 
   for (i=0;i<this.rows;i++){ 
    //循环列 
    for (j=0;j<this.cols;j++){ 
     //寻找开始列 
     for (k=j;k<this.cols;k++){ 
      if (container[i][k]==0) { 
       this.beginCol=k; 
       k=this.cols; //退出循环 
      } 
     } 

      //赋值 
      //此处相应跟改 根据 标签的类型,替换相关参数 
      this.oSheet.Cells(i+1+this.fromrow,this.beginCol+1).value = this.ChangeElementToLabel(this.table.rows(i).cells(j)); 
      //计算合并列 
      try{ 
     this.colSpans = this.table.rows(i).cells(j).colSpan; 
      }catch(e){ 
     this.colSpans=0   
     } 
     if (this.colSpans>1) { 
      //合并 
      this.oSheet.Range(this.oSheet.Cells(i+1+this.fromrow,this.beginCol+1),this.oSheet.Cells(i+1+this.fromrow,this.beginCol+this.colSpans)).Merge(); 
     } 
     //将当前table位置填写到对应的容器中 
     for (k=0; k<this.colSpans;k++) { 
      container[i][this.beginCol+k]= 1; 
     } 
     // 计算合并行 
    
     try{ 
      this.rowSpans = this.table.rows(i).cells(j).rowSpan; 
       }catch(e){ 
       this.rowSpans = 0; 
     } 
    
     if (this.rowSpans>1) { //行合并 
      this.oSheet.Range(this.oSheet.Cells(i+1+this.fromrow,this.beginCol+1),this.oSheet.Cells(i+this.rowSpans+this.fromrow,this.beginCol+this.colSpans)).Merge(); 
      //将当前table位置填写到对应的容器中 
      for (k=1; k<this.rowSpans;k++) { //由于第0行已经被colSpans对应的代码填充了,故这里从第1行开始 
       for (l=0;l<this.colSpans;l++) { 
        container[i+k][this.beginCol+l]=1; 
       } 
      } 
     } 
     //如果开始列+合并列已经等于列数了,故不需要再循环html table 
     if (this.beginCol+this.colSpans>=this.cols) j=this.cols; 
   
    } 
    if(i==0) 
    { 
     //标题栏 
     this.oSheet.Range(this.oSheet.Cells(1,1), this.oSheet.Cells(1,1)).Font.Size=20; 
     this.oSheet.Range(this.oSheet.Cells(1,1), this.oSheet.Cells(1,1)).Font.Bold = true; 
     this.oSheet.Range(this.oSheet.Cells(1,1), this.oSheet.Cells(1,1)).HorizontalAlignment = -4108; //居中 
     this.oSheet.Range(this.oSheet.Cells(1,1), this.oSheet.Cells(1,1)).Rows.RowHeight = 40; 
    } 
     //自动调整行高 
   } 
  
   //最后一行是否空色 
   try{ 
    this.oSheet.Range(this.oSheet.Cells(this.rows,1), this.oSheet.Cells(this.rows,1)).Font.Color=this.lastRowColor; 
   }catch(e){} 

   this.oSheet.Range(this.oSheet.Cells(this.fromrow+2,1), this.oSheet.Cells(this.fromrow+this.rows,this.cols)).Rows.RowHeight=20; 
   this.oSheet.Range(this.oSheet.Cells(this.fromrow+2,1), this.oSheet.Cells(this.fromrow+this.rows,this.cols)).Font.Size=10; 
   //自动换行 
   this.oSheet.Range(this.oSheet.Cells(this.fromrow+2,1), this.oSheet.Cells(this.fromrow+this.rows,this.cols)).WrapText = true; 
   //自动调整列宽 
   this.oSheet.Range(this.oSheet.Cells(this.fromrow+1,1), this.oSheet.Cells(this.fromrow+this.rows,this.cols)).Columns.AutoFit();
//加实线 
   this.oSheet.Range(this.oSheet.Cells(this.fromrow+1,1), this.oSheet.Cells(this.fromrow+this.rows,this.cols)).Borders.LineStyle =1;
   //点虚线 
   //this.oSheet.Range(this.oSheet.Cells(this.fromrow+1,1), this.oSheet.Cells(this.fromrow+this.rows,this.cols)).Borders.LineStyle = -4118; 
  
   return this.rows; 
} 

function test(tabId){ 
// JavaScript Document 
//调用方法 
var test=new PageToExcel(tabId,0,255,"测试.xls");//table id , 第几行开始,最后一行颜色 ,保存的文件名 
test.CreateExcel(false); 
test.Exec(); 
test.SaveAs(); 
test.CloseExcel(); 
//LastRowColor 0黑色 255红色 
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
vxe-table是一个基于Vue.js的数据表格组件,它支持导出Excel、CSV、PDF等格式的表格数据。 要实现合并导出,需要先在vxe-table中设置好需要合并的行,然后再通过导出功能将合并后的表格数据导出。 以下是一个简单的示例代码: ```html <template> <vxe-table :data="tableData" :columns="tableColumns" ref="table"></vxe-table> <el-button @click="exportTable">导出表格</el-button> </template> <script> import Vue from 'vue' import VXETable from 'vxe-table' import 'vxe-table/lib/style.css' Vue.use(VXETable) export default { data() { return { tableData: [ { name: '张三', age: 20, gender: '男', address: '北京市' }, { name: '李四', age: 18, gender: '女', address: '上海市' }, { name: '王五', age: 22, gender: '男', address: '广州市' }, { name: '赵六', age: 16, gender: '女', address: '深圳市' } ], tableColumns: [ { title: '姓名', key: 'name', rowspan: 2 }, { title: '年龄', key: 'age', rowspan: 2 }, { title: '性别', key: 'gender', rowspan: 2 }, { title: '地址', key: 'address', rowspan: 2 } ] } }, methods: { exportTable() { // 获取合并后的表格数据 const data = this.$refs.table.getTableData(true) // 导出Excel this.$tableToExcel(data, { filename: '表格数据.xlsx' }) } } } </script> ``` 在上面的代码中,我们通过设置`rowspan`属性来合并姓名、年龄、性别和地址四的行。然后,通过`this.$refs.table.getTableData(true)`方法获取合并后的表格数据,并将其导出Excel文件。 需要注意的是,在导出Excel文件之前,需要先安装xlsx和file-saver两个依赖包,并在Vue项目中引入。可以通过以下命令来安装: ``` npm install xlsx file-saver --save ``` 然后,在Vue组件中引入: ```js import XLSX from 'xlsx' import FileSaver from 'file-saver' Vue.prototype.$tableToExcel = function(data, { header, filename } = {}) { const sheet = XLSX.utils.json_to_sheet(data, { header: header || Object.keys(data[0]) }) const workbook = XLSX.utils.book_new() XLSX.utils.book_append_sheet(workbook, sheet, 'Sheet1') const blob = new Blob([XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })], { type: 'application/octet-stream' }) FileSaver.saveAs(blob, filename || 'table.xlsx') } ``` 上面的代码中,我们定义了`$tableToExcel`方法,它接受两个参数:表格数据和导出选项。该方法使用xlsx库将数据转换为Excel文件,并使用file-saver库将文件保存到本地。 至此,我们就成功地实现了vxe-table组件中合并导出的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值