问题
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_sheetis 2 dimensional array.- The array length of the 1st index of
output_data_sheetis15 - 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.
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.
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