1. 程式人生 > >javscript 導出html中的table到excel

javscript 導出html中的table到excel

文件 背景顏色 logs ted ons element fonts 釋放 自定義

<script language="JavaScript" type="text/javascript">
 /* * 默認轉換實現函數,如果需要其他功能,需自行擴展
 * 參數:
 * tableID : HTML中Table對象id屬性值
 * 詳細用法參見以下 TableToExcel 對象定義 
 */
 function saveAsExcel(tableID){
  var tb = new TableToExcel(tableID);
  tb.setFontStyle("Courier New");
  tb.setFontSize(10);
  tb.setTableBorder(2);
  tb.setColumnWidth(7);
  tb.isLineWrap(true);
  tb.getExcelFile();
 } 
 /** 功能:HTML中Table對象轉換為Excel通用對象.
  * 參數:tableID HTML中Table對象的ID屬性值
  * 說明:
  * 能適應復雜的HTML中Table對象的自動轉換,能夠自動根據行列擴展信息
  * 合並Excel中的單元格,客戶端需要安裝有Excel
  * 詳細的屬性、方法引用說明參見:Excel的Microsoft Excel Visual Basic參考
  * 示範:
  * var tb = new TableToExcel(‘demoTable‘);
  * tb.setFontStyle("Courier New");
  * tb.setFontSize(10); //推薦取值10
  * tb.setFontColor(6); //一般情況不用設置
  * tb.setBackGround(4); //一般情況不用設置
  * tb.setTableBorder(2); //推薦取值2
  * tb.setColumnWidth(10); //推薦取值10
  * tb.isLineWrap(false);
  * tb.isAutoFit(true);
  * * tb.getExcelFile();
  * 如果設置了單元格自適應,則設置單元格寬度無效
  * 版本:1.0*/
  function TableToExcel(tableID) {
   this.tableBorder = -1; //邊框類型,-1沒有邊框 可取1/2/3/4
   this.backGround = 0; //背景顏色:白色 可取調色板中的顏色編號 1/2/3/4....
   this.fontColor = 1; //字體顏色:黑色
   this.fontSize = 10; //字體大小
   this.fontStyle = "宋體"; //字體類型
   this.rowHeight = 20; //行高
   this.columnWidth = -1; //列寬
   this.lineWrap = true; //是否自動換行
   this.textAlign = -4108; //內容對齊方式 默認為居中
   this.autoFit = true; //是否自適應寬度
   this.tableID = tableID; 
  }
   TableToExcel.prototype.setTableBorder = function (excelBorder) {
    this.tableBorder = excelBorder ;
   }; 
   TableToExcel.prototype.setBackGround = function (excelColor) {
    this.backGround = excelColor;
   }; 
   TableToExcel.prototype.setFontColor = function (excelColor) {
    this.fontColor = excelColor;
   }; 
   TableToExcel.prototype.setFontSize = function (excelFontSize) {
    this.fontSize = excelFontSize;
   }; 
   TableToExcel.prototype.setFontStyle = function (excelFont) {
    this.fontStyle = excelFont;
   }; 
   TableToExcel.prototype.setRowHeight = function (excelRowHeight) {
    this.rowHeight = excelRowHeight;
   }; 
   TableToExcel.prototype.setColumnWidth = function (excelColumnWidth) {
    this.columnWidth = excelColumnWidth;
   }; 
   TableToExcel.prototype.isLineWrap = function (lineWrap) {
    if (lineWrap == false || lineWrap == true) {
     this.lineWrap = lineWrap;
    }
   }; 
   TableToExcel.prototype.setTextAlign = function (textAlign) {
    this.textAlign = textAlign;
   }; 
   TableToExcel.prototype.isAutoFit = function(autoFit){
    if(autoFit == true || autoFit == false)this.autoFit = autoFit ;
   }
   //文件轉換主函數
   TableToExcel.prototype.getExcelFile = function () {
   var jXls, myWorkbook, myWorksheet, myHTMLTableCell, myExcelCell, myExcelCell2;
   var myCellColSpan, myCellRowSpan; 
   try {
    jXls = new ActiveXObject(‘Excel.Application‘);
   }catch (e) {
    alert("無法啟動Excel!\n\n如果您確信您的電腦中已經安裝了Excel,"+"那麽請調整IE的安全級別。\n\n具體操作:\n\n"+"工具 → Internet選項 → 安全 → 自定義級別 → 對沒有標記為安全的ActiveX進行初始化和腳本運行 → 啟用");
    return false;
   } 
   jXls.Visible = true;
   myWorkbook = jXls.Workbooks.Add();
   jXls.DisplayAlerts = false;
   myWorkbook.Worksheets(3).Delete();
   myWorkbook.Worksheets(2).Delete();
   jXls.DisplayAlerts = true;
   myWorksheet = myWorkbook.ActiveSheet; 
   var readRow = 0, readCol = 0;var totalRow = 0, totalCol = 0;
   var tabNum = 0; 
   //設置行高、列寬
   if(this.columnWidth != -1)
    myWorksheet.Columns.ColumnWidth = this.columnWidth;
   else
    myWorksheet.Columns.ColumnWidth = 7;
   if(this.rowHeight != -1)
    myWorksheet.Rows.RowHeight = this.rowHeight ; 
   //搜索需要轉換的Table對象,獲取對應行、列數
   var obj = document.all.tags("table");
   for (x = 0; x < obj.length; x++) {
    if (obj[x].id == this.tableID) {
     tabNum = x;
     totalRow = obj[x].rows.length;
     for (i = 0; i < obj[x].rows[0].cells.length; i++) {
      myHTMLTableCell = obj[x].rows(0).cells(i);
      myCellColSpan = myHTMLTableCell.colSpan;
      totalCol = totalCol + myCellColSpan;
     }
    }
   } 
   //開始構件模擬表格
   var excelTable = new Array();
   for (i = 0; i <= totalRow; i++) {
    excelTable[i] = new Array();
    for (t = 0; t <= totalCol; t++) {
     excelTable[i][t] = false;
    }
   } 
   //開始轉換表格 
   for (z = 0; z < obj[tabNum].rows.length; z++) {
    readRow = z + 1;
    readCol = 0;
    for (c = 0; c < obj[tabNum].rows(z).cells.length; c++) {
     myHTMLTableCell = obj[tabNum].rows(z).cells(c);
     myCellColSpan = myHTMLTableCell.colSpan;
     myCellRowSpan = myHTMLTableCell.rowSpan;
     for (y = 1; y <= totalCol; y++) {
      if (excelTable[readRow][y] == false) {
       readCol = y;
       break;
      }
     }
     if (myCellColSpan * myCellRowSpan > 1) {
      myExcelCell = myWorksheet.Cells(readRow, readCol);
      myExcelCell2 = myWorksheet.Cells(readRow + myCellRowSpan - 1, readCol + myCellColSpan - 1);
      myWorksheet.Range(myExcelCell, myExcelCell2).Merge();
      myExcelCell.HorizontalAlignment = this.textAlign;
      myExcelCell.Font.Size = this.fontSize;
      myExcelCell.Font.Name = this.fontStyle;
      myExcelCell.wrapText = this.lineWrap;
      myExcelCell.Interior.ColorIndex = this.backGround;
      myExcelCell.Font.ColorIndex = this.fontColor;
      if(this.tableBorder != -1){
       myWorksheet.Range(myExcelCell, myExcelCell2).Borders(1).Weight = this.tableBorder ;
       myWorksheet.Range(myExcelCell, myExcelCell2).Borders(2).Weight = this.tableBorder ;
       myWorksheet.Range(myExcelCell, myExcelCell2).Borders(3).Weight = this.tableBorder ;
       myWorksheet.Range(myExcelCell, myExcelCell2).Borders(4).Weight = this.tableBorder ;
      } 
      myExcelCell.Value = myHTMLTableCell.innerText;
      for (row = readRow; row <= myCellRowSpan + readRow - 1; row++) {
       for (col = readCol; col <= myCellColSpan + readCol - 1; col++) {
        excelTable[row][col] = true;
       }
      } 
      readCol = readCol + myCellColSpan;
     } else {
      myExcelCell = myWorksheet.Cells(readRow, readCol);
      myExcelCell.Value = myHTMLTableCell.innerText;
      myExcelCell.HorizontalAlignment = this.textAlign;
      myExcelCell.Font.Size = this.fontSize;
      myExcelCell.Font.Name = this.fontStyle;
      myExcelCell.wrapText = this.lineWrap;
      myExcelCell.Interior.ColorIndex = this.backGround;
      myExcelCell.Font.ColorIndex = this.fontColor;
      if(this.tableBorder != -1){
       myExcelCell.Borders(1).Weight = this.tableBorder ;
       myExcelCell.Borders(2).Weight = this.tableBorder ;
       myExcelCell.Borders(3).Weight = this.tableBorder ;
       myExcelCell.Borders(4).Weight = this.tableBorder ;
      }
      excelTable[readRow][readCol] = true;readCol = readCol + 1;
     }
    }
   }
   if(this.autoFit == true)
    myWorksheet.Columns.AutoFit; 
   jXls.UserControl = true;
   jXls = null;
   myWorkbook = null;
   myWorksheet = null;
  };

 

以下內容為網絡搜集,方便自己使用。出處不詳(我忘了從哪找的了,呵呵)。
-------------------------------------------------------------------------------------------------------------------------------------
使用JavaScript中的ActiveXObject填充並設置Excel格式
1.創建實例並創建工作表
var XLObj = new ActiveXObject("Excel.Application");//創建Excel實例
var xlBook = XLObj.Workbooks.Add;                         //新增工作簿
var ExcelSheet = xlBook.Worksheets(1);                   //創建工作表
2.保存表格
ExcelSheet.SaveAs("C:\\TEST.XLS");
3.使 Excel 通過 Application 對象可見
ExcelSheet.Application.Visible = true;或者ExcelSheet.Visible=true;
4.打印
xlBook.PrintOut;或者:ExcelSheet.PrintOut;
5.關閉
xlBook.Close(savechanges=false);或者ExcelSheet.Close(savechanges=false);
6.結束進程
ExcelSheet.Application.Quit()或者XLObj.Quit(); XLObj=null;
7.頁面設置
ExcelSheet.ActiveSheet.PageSetup.LeftMargin= 2/0.035;         //頁邊距 左2厘米
ExcelSheet.ActiveSheet.PageSetup.RightMargin = 3/0.035;      //頁邊距 右3厘米,
ExcelSheet.ActiveSheet.PageSetup.TopMargin = 4/0.035;        //頁邊距 上4厘米,
ExcelSheet.ActiveSheet.PageSetup.BottomMargin = 5/0.035;   //頁邊距 下5厘米
ExcelSheet.ActiveSheet.PageSetup.HeaderMargin = 1/0.035;   //頁邊距 頁眉1厘米
ExcelSheet.ActiveSheet.PageSetup.FooterMargin = 2/0.035;    //頁邊距 頁腳2厘米
ExcelSheet.ActiveSheet.PageSetup.CenterHeader = "頁眉中部內容";
ExcelSheet.ActiveSheet.PageSetup.LeftHeader = "頁眉左部內容";
ExcelSheet.ActiveSheet.PageSetup.RightHeader = "頁眉右部內容";
ExcelSheet.ActiveSheet.PageSetup.CenterFooter = "頁腳中部內容";
ExcelSheet.ActiveSheet.PageSetup.LeftFooter = "頁腳左部內容";
ExcelSheet.ActiveSheet.PageSetup.RightFooter = "頁腳右部內容";
8.對單元格操作,帶*部分對於行,列,區域都有相應屬性
ExcelSheet.ActiveSheet.Cells(row,col).Value = "內容";                //設置單元格內容
ExcelSheet.ActiveSheet.Cells(row,col).Borders.Weight = 1;        //設置單元格邊框*()
ExcelSheet.ActiveSheet.Cells(row,col).Interior.ColorIndex = 1;    //設置單元格底色*(1-黑色,2-白色,3-紅色,4-綠色,5-藍色,6-黃色,7-粉紅色,8-天藍色,9-醬土色..可以多做嘗試)
ExcelSheet.ActiveSheet.Cells(row,col).Interior.Pattern = 1;         //設置單元格背景樣式*(1-無,2-細網格,3-粗網格,4-斑點,5-橫線,6-豎線..可以多做嘗試)
ExcelSheet.ActiveSheet.Cells(row,col).Font.ColorIndex = 1;        //設置字體顏色*(與上相同)
ExcelSheet.ActiveSheet.Cells(row,col).Font.Size = 10;                //設置為10號字*
ExcelSheet.ActiveSheet.Cells(row,col).Font.Name = "黑體";        //設置為黑體*
ExcelSheet.ActiveSheet.Cells(row,col).Font.Italic = true;             //設置為斜體*
ExcelSheet.ActiveSheet.Cells(row,col).Font.Bold = true;             //設置為粗體*
ExcelSheet.ActiveSheet.Cells(row,col).ClearContents;                //清除內容*
ExcelSheet.ActiveSheet.Cells(row,col).WrapText=true;               //設置為自動換行*
ExcelSheet.ActiveSheet.Cells(row,col).HorizontalAlignment = 3; //水平對齊方式枚舉* (1-常規,2-靠左,3-居中,4-靠右,5-填充 6-兩端對齊,7-跨列居中,8-分散對齊)
ExcelSheet.ActiveSheet.Cells(row,col).VerticalAlignment = 2;      //垂直對齊方式枚舉*(1-靠上,2-居中,3-靠下,4-兩端對齊,5-分散對齊)
//行,列有相應操作:
    ExcelSheet.ActiveSheet.Rows(row).
    ExcelSheet.ActiveSheet.Columns(col).
    ExcelSheet.ActiveSheet.Rows(startrow+":"+endrow).                   //如Rows("1:5")即1到5行
    ExcelSheet.ActiveSheet.Columns(startcol+":"+endcol).                //如Columns("1:5")即1到5列
    //區域有相應操作:
    XLObj.Range(startcell+":"+endcell).Select;
        //如Range("A2:H8")即A列第2格至H列第8格的整個區域
    XLObj.Selection.
    //合並單元格
    XLObj.Range(startcell+":"+endcell).MergeCells = true;
        //如Range("A2:H8")即將A列第2格至H列第8格的整個區域合並為一個單元格
    或者:XLObj.Range("A2",XLObj.Cells(8, 8)).MergeCells = true;
9.設置行高與列寬
ExcelSheet.ActiveSheet.Columns(startcol+":"+endcol).ColumnWidth = 22;//設置從firstcol到stopcol列的寬度為22
ExcelSheet.ActiveSheet.Rows(startrow+":"+endrow).RowHeight = 22;//設置從firstrow到stoprow行的寬度為22
Var myrange oSheet.Range(oSheet.Cells(2,1),oSheet.Cells(2,6));
myRange.Columns.AutoFit()
myRange.Rows.AutoFit()//好像不太管用
//設置該區域為自適應高度和寬度
使用JavaScript將表格內容導出到Excel的方式
1.整個表格拷貝到EXCEL中 
function CopyTable(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可見屬性 
} 
2.把單元格內容拷貝到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;
     var y=document.getElementById(‘dropYear‘);
     var m=document.getElementById(‘dropMonth‘);
     //取得表格行數
     oSheet.Cells( 1, 1).value=‘商戶名稱:工商銀行商城‘;
     oSheet.Range(oSheet.Cells(1,1),oSheet.Cells(1,6)).Merge()
     oSheet.Cells(2,1).value=日期; ‘+y.options[y.selectedIndex].value+‘-‘+m.options[m.selectedIndex].value;
     oSheet.Range(oSheet.Cells(2,1),oSheet.Cells(2,6)).Merge()
     oSheet.Cells( 3, 1).value=‘銷售情況‘
     oSheet.Range(oSheet.Cells(3,1),oSheet.Cells(3,6)).Merge()
     oSheet.Cells( 3, 1).HorizontalAlignment=3;
     oSheet.Cells( 3, 1).Font.Size=14;
     oSheet.Cells( 3, 1).Font.Bold = true;
     oSheet.Range(oSheet.Cells(4,1),oSheet.Cells(4,6)).Merge()
     oSheet.Cells(4,1).value=document.getElementById(‘lbMessage‘).innerText;
     for (i = 0; i < Lenr; i++)
     {
     var Lenc = curTbl.rows(i).cells.length;
//取得每行的列數
         for (j = 0; j < Lenc; j++)
         {
             oSheet.Cells(i + 5, j + 1).value = curTbl.rows(i).cells(j).innerText;
             //賦值
         }
     }
     oSheet.Cells(i+6,2).value=document.getElementById(‘hidSum‘).value;
     oSheet.Columns.AutoFit();
     oSheet.Rows.AutoFit();
     oSheet.Rows(4).RowHeight = 30;
     oXL.Visible = true;
     //設置excel可見屬性
     oXL.Quit();
     oXL = null;
     idTmr = window.setInterval("Cleanup();",1);//強制釋放資源
}
function Cleanup()//清除Excel資源
{
     window.clearInterval(idTmr);
     CollectGarbage();
}
使用JavaScript按照表格格式復制內容到剪切板
1.在Excel中進行粘貼
function copytable()
{
    var content=‘‘
    var tb=document.getElementById(‘GVmain‘);
    var rows=tb.rows;
    for(var i=0;i<rows.length;i++)
    {
          var cells=rows[i].cells;
          for(var j=0;j<cells.length;j++)
          {
              content +=cells[j].innerText.toString()+‘\t‘;
          }
         content +=‘\n‘;
     }
     if(content!=‘‘)
     {
         clipboardData.setData("text",content);
         alert("復制成功!")
     }
}

  本文選自 http://www.cnblogs.com/lhws/archive/2012/03/15/2397952.html

javscript 導出html中的table到excel