日期:2014-05-16  浏览次数:20453 次

js实现xml数据的导出功能
function ExpXmlToExcel(xmlDoc)
{
var xmlField="<FIELDLIST><userid>编号</userid><username>姓名</username></FIELDLIST>";
function createXMLDOM()
{
var xmlDoc = null;
//通过对象/属性检测法,判断是IE来是Mozilla
if (!window.DOMParser  && window.ActiveXObject)
{
  var arrVersions= ["MSXML2.DOMDocument.5.0","MSXML2.DOMDocument.4.0",
   "MSXML2.DOMDocument.3.0","MSXML2.DOMDocument", "Microsoft.XmlDoc"];
  for (var i=0; i < arrVersions.length; i++)
  {
try
{
  xmlDoc = new ActiveXObject(arrVersions[i]);
  return xmlDoc;            
}
catch (oError)
{
   //忽略,继续
}
  }          
  throw new Error("系统没有安装MSXML");   
 
   }else if(xmlDoc == null && document.implementation && document.implementation.createDocument)
   {    // Mozilla browsers have a DOMParser
  try{
xmlDoc = document.implementation.createDocument("","",null);
return xmlDoc;
}catch (ex){}
   }else 
   {
   throw   new  Error( " Your browser doesn't support an XML DOM object. " );
   }
}
if(window.DOMParser){
Document.prototype.loadXML = function(sXml){
var oParser= new DOMParser();
var _xmlDom = oParser.parseFromString(sXml, "text/xml");
while(this.firstChild){
   this.removeChild(this.firstChild);
}

for(var i=0;i<_xmlDom.childNodes.length;i++){
var oNewNode = this.importNode(_xmlDom.childNodes[i],true);
this.appendChild(oNewNode);
}
}
}
//导入xml字符串
var nodesList = xmlDoc.getElementsByTagName("user");

//导入字段列表;
var xmlDocField = new createXMLDOM();
xmlDocField.loadXML(xmlField);
var fieldList = xmlDocField.documentElement.childNodes;

// Start Excel and get Application object.
var oXL = new ActiveXObject("Excel.Application");
// Get a new workbook.
var oWB = oXL.Workbooks.Add();
var oSheet = oWB.ActiveSheet;
var hang = nodesList.length;
var lie = fieldList.length;
//插入表头

for (var j=0;j<lie;j++)
{
oSheet.Cells(1,j+1).value = fieldList[j].text;
}

// Add table headers going cell by cell.
for (var i=0;i<hang;i++)
{
for (var j=0;j<lie;j++)
{
oSheet.Cells(i+2,j+1).value = getXmlTagValue(nodesList[i],fieldList[j].nodeName);
}
}
oXL.Visible = true;
oXL.UserControl = true;
}