使用Office-JS删除Excel表中的行

米佐达勒

我在add中有一个ajax调用,它应该在excel中创建或更新表。如果表已经存在,则应删除行并添加新结果。当删除循环中的行时,它正在删除一些行,然后出现以下错误:

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://zh.wikipedia.org/wiki/链接列表

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


另一种方法

用普通的for循环开始循环。颠倒了。例如:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章