我正在使用Martin Hawksey的Google Apps脚本的修改版本,该脚本将我的一张工作表中的数据存储在Google电子表格中,另一张工作表为我的事件描述列中的每个条目创建了一个新行(由逗号 - 即单元格D2 ="描述1,描述2,描述3等)。虽然这非常有效,但我希望它能够再做一个功能 - 我希望它能够在事件描述中使用最后一个条目(可能用分号而不是逗号分隔其他条目)并将其推入删除分号或其他分隔符时,每个唯一事件一次且仅一次相邻单元格。我尝试了很多方法,但对Google Apps脚本不熟悉,我没有成功。
function splitColumnAndRepeatRows(anArray, splitColumnIndex) {
var output = [];
for (i in anArray){ // for each row
var splitArray = anArray[i][splitColumnIndex].toString().split(","); // split values in specified column
for (j in splitArray){ // for each split cell value
if(splitArray[j]=="" && j>=1)
continue;
var row = anArray[i].slice(0); // take a copy of source row
row[splitColumnIndex] = alltrim(splitArray[j]); // replace comma separated value with current split value
output.push(row); // push new row to output
}
}
return output;
}
function alltrim(str) {
return str.replace(/^\s+|\s+$/g, '');
}
基本上,这就是我试图做的事情 - 转过来:
Date Client County Description
9/21/14 12345 Greene Location 1, Location 2, Location 3; Y
9/24/14 54321 Brown Location 1, Location 2; X
进入这个:
Date Client County Description Time
9/21/14 12345 Greene Location 1
9/21/14 12345 Greene Location 2
9/21/14 12345 Greene Location 3 Y
9/24/14 54321 Brown Location 1
9/24/14 54321 Brown Location 2 X
任何帮助将不胜感激!
谢谢!
答案 0 :(得分:1)
这个经过编辑的splitColumnAndRepeatRows()函数将完成您所追求的工作,并且您的列中任何(不仅仅是最后一个)逗号分隔项可以是一个额外的奖励: - 分隔列表并将分成2个单元格
function splitColumnAndRepeatRows(anArray, splitColumnIndex) {
var output = [];
for (var i in anArray){ // for each row
var splitArray = anArray[i][splitColumnIndex].toString().split(","); // split values in specified column
for (var j in splitArray){ // for each split cell value
if(splitArray[j]=="" && j>=1)
continue;
var row = anArray[i].slice(0); // take a copy of source row
var trimmedString = alltrim(splitArray[j]);
var subArray = trimmedString.split(";"); // split current item of specified column at ;
if ( subArray.length > 1 ) { // if current item is a ;-delimited list (now split into an array)
row[splitColumnIndex] = alltrim(subArray[0]); // replace comma-separated value with first item of ;-delimited array
row[splitColumnIndex+1] = alltrim(subArray[1]); // append second item of ;-delimited list as new cell to row
}
else {
row[splitColumnIndex] = trimmedString; // replace comma separated value with current split value
row[splitColumnIndex+1] = ""; // append empty cell to row
}
output.push(row); // push new row to output
}
}
return output;
}
它可以变成这样的东西:
9/21/14 12345 Greene Location 1; A, Location 2, Location 3; B
9/24/14 54321 Brown Location 1, Location 2; C
进入这个:
9/21/14 12345 Greene Location 1 A
9/21/14 12345 Greene Location 2
9/21/14 12345 Greene Location 3 B
9/24/14 54321 Brown Location 1
9/24/14 54321 Brown Location 2 C