2

Currently I'm triying to find a solution that helps me to storage the content of the worksheets in some place like localstorage for example.

async backupSheets() {
 await Excel.run(async (context) => {
  var worksheets = context.workbook.worksheets;
  worksheets.load('items');
  await context.sync();
  let wsBackup = worksheets;
  
  
  for (var i = 0; i < worksheets.items.length; i++) {
    console.log(worksheets.items[i].toJSON());
    worksheets.items[i].delete();
  }
  //There will be some code to restore the workshets currently with:
  worksheets = wsBackup;
  //But it doesn't works.

  await context.sync();
 });
}

The expected behavior is when I do the assigment worksheets = wsBackup it restore the worksheets that I saved before the delete loop. Currently this isn't working and I'm triying to find a workaround for this.

An Excel scenario should be..

  • Copy all the worksheets in a variable called wsBackup
  • Delete all worksheets except the last
  • The proxy object that I used for it should be restored with the assigment of the backup wsBackup
  • The worksheets should be restored properly in the workbook

The actual behavior that I got is all the steps except the restored worksheets.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
cgodev
  • 21
  • 2

1 Answers1

1

When you assign a JavaScript object to another variable, you are assigning-by-reference, not assigning-by-value. So both worksheets and wsbackup are pointing to the same object in memory. When you delete the members of the worksheets.items property, you are also deleting the members of the wsbackup.items property, since worksheets and wsbackup are the same object. See this Stack answer for more: JavaScript's assignment operation is to copy references.

Try replacing the line let wsBackup = worksheets; with the lines:

let wsbackup = context.workbook.worksheets;
wsbackup.load('items');

These lines will create an entirely new proxy object and load it's items.

Rick Kirkham
  • 9,038
  • 1
  • 14
  • 32