萬盛學電腦網

 萬盛學電腦網 >> 網頁制作 >> 腳本Html教程 >> ASP.NET的HTMLTable原樣導出到Excel

ASP.NET的HTMLTable原樣導出到Excel

   function PrintTableToExcelEx(objTab)

  ...{

  try

  ...{

  var xls = new ActiveXObject( "Excel.Application" );

  }

  catch(e)

  ...{

  alert( "您必須安裝Excel電子表格軟件,同時浏覽器須使用“ActiveX 控件”,您的浏覽器須允許執行控件。 請點擊【幫助】了解浏覽器設置方法!");

  return false;

  }

  xls.visible = true;

  var xlBook = xls.Workbooks.Add;

  var xlsheet = xlBook.Worksheets(1);

  var CurX = 1;

  var CurY = 1;

  for (var i = 0; i < objTab.rows.length; i++)

  ...{

  for (var j = 0; j < objTab.rows[i].cells.length; j++)

  ...{

  var cell = objTab.rows[i].cells[j];

  var v = cell.outerText;

  if ( cell.children != null && cell.children.length != 0 )

  ...{

  v = "";

  for ( var k = 0; k < cell.children.length; k++ )

  ...{

  var cc = cell.children[k];

  switch (cc.type)

  ...{

  case "select-one":

  for ( var l = 0; l < cc.options.length; l++ )

  if ( cc.options[l].selected )  v += cc.options[l].text;

  break;

  case "text":

  v += cc.value;

  break;

  case "checkbox":

  v += cc.checked ? "是" : "否";

  break;

  case undefined:

  v += cell.outerText;

  break;

  case "hidden":

  break;

  default:

  //v += cc.id + "/";

  //v += cc.tagname + "/";

  //v += cc.type + "/"

  v += cc.value;

  break;

  }

  }

  }

  while ( xlsheet.Cells(CurX,CurY).MergeCells )    CurY++;

  xlsheet.Cells(CurX, CurY).HorizontalAlignment = 2;

  var align = cell.getAttribute("align");

  switch ( align )

  ...{

  case "left":

  xlsheet.Cells(CurX, CurY).HorizontalAlignment = 2;//XlHalign.xlHalignLeft;

  break;

  case "center":

  xlsheet.Cells(CurX, CurY).HorizontalAlignment = 3;;//XlHalign.xlHalignCenter;

break;
case "right":
xlsheet.Cells(CurX, CurY).HorizontalAlignment = 4;//XlHalign.xlHalignRight;
break;
}
xlsheet.Cells(CurX, CurY).WrapText = true;
xlsheet.Cells(CurX, CurY).VerticalAlignment = 2;
xlsheet.Cells(CurX, CurY).Value = v;
xlsheet.Cells(CurX, CurY).Borders.LineStyle = 1;

var rowSpan = cell.getAttribute("RowSpan");
var colSpan = cell.getAttribute("ColSpan");
if ( rowSpan >= 2 || colSpan >= 2 )
...{
var R = xls.Range(xls.Cells(CurX, CurY), xls.Cells(CurX + rowSpan - 1, CurY + colSpan - 1));
R.MergeCells = true;
R.Borders.LineStyle = 1;
}
CurY++;            
}

CurX++;
CurY = 1;
}
xlsheet.Columns.AutoFit; //自動適應大小
return;
}

  調用:

<INPUT style="WIDTH: 107px" onclick="javascript:PrintTableToExcelEx(Table1)" type="button" value="導 出" class="input">

copyright © 萬盛學電腦網 all rights reserved