Exception: The number of columns in the data does not match the number of columns in the range despite the range being created from data

怎甘沉沦 提交于 2020-08-10 23:39:29

问题


I'm trying to figure out what I'm missing here in this Google script. I keep getting the error

Exception: The number of columns in the data does not match the number of columns in the range. The data has 0 but the range has 15.

but it doesn't make sense to me.

Here's the bit of code in question:

var range = ReleaseSchedule.getRange(1,1,output_data_sheet.length,output_data_sheet[0].length);
range.setValues(output_data_sheet);

ReleaseSchedule is a new sheet in the active spreadsheet output_data_sheet is a 2 dimensional array. I have similar code working earlier in the script, but for some reason this one is throwing that exception and I can't figure out why. Any help or thoughts would be greatly appreciated.


回答1:


I thought that the reason of this error of Exception: The number of columns in the data does not match the number of columns in the range. The data has 0 but the range has 15. might be as follows.

  • output_data_sheet is 2 dimensional array.
  • The array length of the 1st index of output_data_sheet is 15
  • The empty array (the array length is 0) is included in the index except for 1st index.

When above output_data_sheet is used for setValues(), such error might occur. In order to remove this issue, how about the following modifications? Here, I would like to propose 2 patterns.

Pattern 1:

In this pattern, the empty elements are removed from output_data_sheet.

From:
var range = ReleaseSchedule.getRange(1,1,output_data_sheet.length,output_data_sheet[0].length);
range.setValues(output_data_sheet);
To:
output_data_sheet = output_data_sheet.filter(String);  // <--- Added
var range = ReleaseSchedule.getRange(1,1,output_data_sheet.length,output_data_sheet[0].length);
range.setValues(output_data_sheet);

Pattern 2:

In this pattern, the empty elements and the element smaller than the length of 15 add the elements for keeping the length of 15 for each index in output_data_sheet.

From:
var range = ReleaseSchedule.getRange(1,1,output_data_sheet.length,output_data_sheet[0].length);
range.setValues(output_data_sheet);
To:
output_data_sheet = output_data_sheet.map(r => r.length == 15 ? r : r.concat(Array(15 - r.length).fill("")));  // <--- Added
var range = ReleaseSchedule.getRange(1,1,output_data_sheet.length,output_data_sheet[0].length);
range.setValues(output_data_sheet);

References:

  • filter()
  • map()


来源:https://stackoverflow.com/questions/62632038/exception-the-number-of-columns-in-the-data-does-not-match-the-number-of-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!