在网页中与EXCEL的交互(导入)

来源:互联网 发布:c语言中括号的用法 编辑:程序博客网 时间:2024/06/05 01:12

function WriteScoreInDG(strNumber, strScore)
{
 var ndgRC = document.all.DataGrid1.rows.length;
 var i, nNumber=parseInt(strNumber);
 var strdgNumber;
 if(isNaN(nNumber))
  return false;
 for(i=1; i<=ndgRC; i++)
 {
  strdgNumber = document.all.DataGrid1.rows(i).cells(0).innerText;
  if (parseInt(strdgNumber) == nNumber)
  {
   document.all.DataGrid1.rows(i).cells(3).childNodes[0].innerText=strScore;
   break;
  }
 }
 if (i>ndgRC)
  return false;
 else
  return true;
}

function loadExcel(strSubject)
{
 document.all.filename.value = "";
 showModalDialog("LoadFile.aspx",window,"dialogWidth=590px;dialogHeight=290px;scroll=no");
 var strFileName = document.all.filename.value;
 var nSheet = parseInt(document.all.sheet.value);
 if (strFileName != "")
 {
  try
  {
   var xlsApp = new ActiveXObject("Excel.Application");
   xlsApp.visible = false;
   var xlsBook = xlsApp.WorkBooks.Open(strFileName);
   var xlsSheet = xlsBook.WorkSheets(nSheet);
   var strScore = "", strNumber = "";
   var nScoreCol = 1, nNumberCol=1, nRow, nSpaceRow, i, nSuccessCount;
   
   //当列没内容,为undefined时不知该如何判断.
   //strScoreName != undefined不行,strScoreName != "undefined"也不行,strScoreName != null也不行.
   //只好向右查20个.
   strScore = xlsSheet.Cells(1, nScoreCol);
   while (strScore != strSubject)
   {
    nScoreCol++;
    strScore = xlsSheet.Cells(1, nScoreCol);
    if (nScoreCol >20)
     break;
   }
   strNumber = xlsSheet.Cells(1, nNumberCol);
   while (strNumber != "学号")
   {
    nNumberCol++;
    strNumber = xlsSheet.Cells(1, nNumberCol);
    if (nNumberCol >20)
     break;
   }
   if (strScore != strSubject)
    alert("找不到成绩列,你的EXCEL文件中应有一列名为“"+strSubject+"”的列");
   else if (strNumber != "学号")
    alert("找不到学号列,你的EXCEL文件中应有一列名为“学号”的列");
   else
   {
    nRow = 2;
    nSpaceRow = 0;
    nSuccessCount = 0;
    //由于无法判断何时结束,所以用当连续5行找不到学号时结束.
    while(nSpaceRow<5)
    {
     strScore = xlsSheet.Cells(nRow, nScoreCol);
     strNumber = xlsSheet.Cells(nRow, nNumberCol);
     if(!WriteScoreInDG(strNumber, strScore))
      nSpaceRow++;
     else
      nSuccessCount++;
     nRow++;
    }
    alert("导入成绩完成,共导入"+nSuccessCount+"个学生成绩。");
   }   
   
   xlsApp.Quit();
   xlsSheet = null;
   xlsBook = null;
   xlsApp = null;
  }
  finally
  {
   xlsApp.Quit();
   xlsSheet = null;
   xlsBook = null;
   xlsApp = null;
  }
 }
 
}

通过如下代码调用如:loadExcel('电脑')。但发现一个很大的问题,这是调用ACTIVEX控件的,调用后没能真正退出EXCEL程序,要在进程中关闭。只能以后再慢慢解决了。 

原创粉丝点击