用office-js删除excel表中的行

我在我的添加ajax调用它应该在Excel中创build或更新表。 如果表已经存在,它应该删除行并添加新的结果。 当在循环中删除行时,它正在删除一些行,然后我得到以下错误:

Debug info: {"code":"InvalidArgument","message":"The argument is invalid or missing or has an incorrect format.","errorLocation":"TableRowCollection.getItemAt"}

我在我的Excel Web插件中的ajax调用如下所示:

 $.ajax({ //.... }).done(function (data) { Excel.run(function (ctx) { var odataTable = ctx.workbook.tables.getItemOrNullObject("odataTable"); //rows items are not available at this point, that is why we need to load them and sync the context odataTable.rows.load(); return ctx.sync().then(function () { if (odataTable.rows.items == null) { odataTable.delete(); odataTable = ctx.workbook.tables.add('B2:G2', true); odataTable.name = "odataTable"; } else { console.log("Rows items:" + odataTable.rows.items.length); odataTable.rows.items.forEach(function (item) { console.log("Removing row item: " + item.values); item.delete(); }); console.log("rows cleaned"); } }).then(function () { //add rows to the table }); }).then(ctx.sync); }).catch(errorHandler); }).fail(function (status) { showNotification('Error', 'Could not communicate with the server. ' + JSON.stringify(status)); }).always(function () { $('#refresh-button').prop('disabled', false); }); 

可迭代集合的思想是它们由不同的项目组成。 一旦你以不恰当的方式从这些项目中删除了一些东西,收集就不再是一个集合。 这是因为它们被实现为链接列表,其中每个单元只知道下一个单元。 https://en.wikipedia.org/wiki/Linked_list

在你的情况下,你正在删除一个for-each循环。 在第一次删除之后,集合被破坏。 因此,你需要另一种方法


另一种方法

开始与循环正常循环。 逆转。 例如:

 for i = TotalRows to 1 i-- if row(i) something then delete