使用javascript删除Excel工作表中的行

时间:2010-01-29 05:53:20

标签: javascript excel activex

我正在尝试使用Javascript中的activex对象编辑Excel工作表。

以下功能打开Excel工作表并创建一些条目。

function test() {
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = ExcelApp.Workbooks.Open("c:\\jan29.xls");
ExcelSheet.Application.Visible = true;

ExcelSheet.ActiveSheet.Cells(0,1).Value = i;

ExcelSheet.Save;
ExcelSheet.Application.Quit();
}

但是如何删除行,获取工作表数量并通过rowColumn获取值。我在哪里可以获得APIS列表?

此致 大额牛

1 个答案:

答案 0 :(得分:1)

您可以找到Developer Reference for Excel 2007 on MSDN以及(有点不守规矩)API Reference

为了直接回答您的问题,我创建了一个包含行删除的演示。

工作演示

(需要IE,Excel和ActiveX权限)
http://jsbin.com/izule(可通过http://jsbin.com/izule编辑)

JavaScript源

function test() {
  if (!window['ActiveXObject']) {
    log('Error: ActiveX not supported');
    return;
  }

  try {
    var
      ExcelApp = new ActiveXObject("Excel.Application"),
      ExcelBook = ExcelApp.Workbooks.Add();

    ExcelBook.Application.Visible = true;
    log('Opened Excel');

    wait(2, enterData);
  }
  catch (ex) {
    log('An error occured while attempting to open Excel');
    console.log(ex);
  }

  function enterData() {
    try {
      ExcelBook.ActiveSheet.Cells(1, 1).Value = 'foo';
      ExcelBook.ActiveSheet.Cells(2, 1).Value = 'bar';
      log('Entered data');
    }
    catch (ex) {
      log('An error occured while attempting to enter data');
      console.log(ex);
    }

    wait(2, deleteRow);
  }

  function deleteRow () {
    try {
      ExcelBook.ActiveSheet.Rows(1).Delete();
      log('Deleted first row');
    }
    catch (ex) {
      log('An error occured while attempting to delete a row');
      console.log(ex);
    }

    wait(2, quitExcel);
  }

  function quitExcel () {
    try {
      // Allow excel to quit without prompting user to save.
      ExcelBook.Saved = true;
      ExcelBook.Application.Quit();
      log('Quit excel');
    }
    catch (ex) {
      log('An error occured while attempting to quit excel');
      console.log(ex);
    }
  }
}

function wait (time, action) {
  setTimeout(action, time * 1000);
}

function log (message) {
  var
    list = document.getElementById('log'),
    newLog = document.createElement('li');
  newLog.innerHTML = message;
  list.appendChild(newLog);
}
if (!window['console'] || !window.console['log']) { console = {log: log}; }