我正在使用 Google Apps 脚本导入 CSV 数据。所有 CSV 数据都已导入,但仍然出现此错误消息:
范围宽度不正确,为 1 但应为 5
我的 CSV 文件是用';'
逗号分隔的,里面也有逗号。我的 CSV 文件中的示例:
FJ32-19A354-AA;'BES_301 - Exterior Trim;'000101;BOM No CAD;04/01/16
总共有 5 列,当我在getRange()
调用中说明列数时,我收到另一个错误:
找不到方法 getRange(number,number,number,number,number)
我目前正在使用的示例代码(改编自“Ask Ben”):
var ss = SpreadsheetApp.openById('1V8YG8lyNZiTllEPHENcnabYRLDPCK6mHGUyAyNhW0Is'); // data_sheet_id = id of spreadsheet that holds the data to be updated with new report data
var s = SpreadsheetApp.getActiveSheet();
var csv = file.getBlob().getDataAsString();
var csvData = CSVToArray(csv); // see below for CSVToArray function
var lastrow = s.getLastRow();
s.getRange(lastrow+ 1, 1,5, csvData.length, csvData[0].length).setValues(csvData);
function CSVToArray( strData, strDelimiter ){
strDelimiter = (strDelimiter || ";");
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
var arrData = [[]];
var arrMatches = null;
while (arrMatches = objPattern.exec( strData )){
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
strMatchedDelimiter.length &&
strMatchedDelimiter !== strDelimiter
){
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push( [] );
}
var strMatchedValue;
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else {
// We found a non-quoted value.
strMatchedValue = arrMatches[ 3 ];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
}
// Return the parsed data.
return( arrData );
}