使用JavaScript搜索和操作Excel数据

时间:2011-11-23 23:05:01

标签: javascript excel activexobject

我有一个HTML网页表单,其中包含5个文本输入和一个调用JavaScript函数的按钮。现在的功能,将打开一个现有的Excel文件,找到最后填充的行,在其下面插入一个新行并将表单值放入,每个单元格中有一个值。然后保存并退出。

然而,电子表格有超过5列,因此该函数只将数据放入A-E列。

function createData(){

    var first = document.getElementById('A').value;
    var second = document.getElementById('B').value;
    var third = document.getElementById('C').value;
    var fourth = document.getElementById('D').value;
    var fifth = document.getElementById('E').value;

    var xlDown = -4121

    var w =new ActiveXObject("Excel.Application");
    w.Visible=true;

    w.Workbooks.Open("file:\\Form.xls");
    objWorksheet = w.Worksheets(1);

    objRange = w.Range("A1");
    objRange.End(xlDown).Activate;
    intNewRow = w.ActiveCell.Row + 1;

    for (i=1; i<10000; i++){
        objWorksheet.Cells(intNewRow, 1) = first;
        objWorksheet.Cells(intNewRow, 2) = second;
        objWorksheet.Cells(intNewRow, 3) = third;
        objWorksheet.Cells(intNewRow, 4) = fourth;
        objWorksheet.Cells(intNewRow, 5) = fifth;
    }
    w.ActiveWorkbook.SaveAs("file:\\Form.xls");
    w.Quit();
              alert("The data has been added to the spreadsheet");
}

我真正想做的是:

电子表格可能已经或可能没有每行中A-G列的数据。 我希望函数在现有工作表的B列中搜索“first”的文本值(如上所述)。如果找到,则将其他4个值插入H-K列中的相应单元格中。如果未找到,则将所有5个值插入B列中的“第一”新行,其余部分插入H-K列。

我已经搞这个很长一段时间,似乎无法破解它,虽然我知道它可以做到。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:3)

好吧,我似乎通过反复试验找到了答案。她不漂亮,但它的确有效。我会考虑在时间允许的情况下优化代码。

function createData(){      

var Name = document.getElementById('txtName').value;

var first = document.getElementById('A').value;     
var second = document.getElementById('B').value;     
var third = document.getElementById('C').value;     
var fourth = document.getElementById('D').value;     
var fifth = document.getElementById('E').value;      
var xlDown = -4121      

var w =new ActiveXObject("Excel.Application");     
w.Visible=true;      
w.Workbooks.Open("file:\\Form.xls");     

objWorksheet = w.Worksheets(1);      
objRange = w.Range("H3");     
objRange.End(xlDown).Activate;     
intNewRow = w.ActiveCell.Row + 1;      

for (i=4; i<10; i++){
    var a = objWorksheet.Cells(i,2);
    var b = a.Value;
    if(b == Name){
        a.Activate;
        b = w.ActiveCell.Offset(0,6);
        intNew = w.ActiveCell.Row;
        objWorksheet.Cells(intNew, 8) = first
        objWorksheet.Cells(intNew, 9) = second
        objWorksheet.Cells(intNew, 10) = third
        objWorksheet.Cells(intNew, 11) = fourth
        objWorksheet.Cells(intNew, 12) = fifth
    }   
    else{
        objWorksheet.Cells(intNewRow, 8) = first
        objWorksheet.Cells(intNewRow, 9) = second
        objWorksheet.Cells(intNewRow, 10) = third
        objWorksheet.Cells(intNewRow, 11) = fourth
        objWorksheet.Cells(intNewRow, 12) = fifth
    }
}
w.ActiveWorkbook.SaveAs("file:\\\\Test.xls");
w.Quit();
}