我正在尝试提出一个函数,该函数将根据分隔符(在本例中为“\n”)将存储在单元格中的数据拆分为多行。我在这里找到了一个非常好的解决方案:
但是,此解决方案仅允许您将一列拆分为多行;我需要拆分多个列。
这是我现在拥有的一些数据的示例:
以下是我希望最终产品的示例:
我知道我可以通过使用 =TRANSPOSE(SPLIT(cell,CHAR(10)))
然后复制其他单元格来获得此结果,但我有很多数据,所以我'我真的更喜欢像上面的链接一样自动化执行此操作。感谢您能给我的任何帮助。谢谢!
最佳答案
重组行以在单个单元格中容纳多个项目
function restructureRows() {
const ss=SpreadsheetApp.getActive();
const sh=ss.getSheetByName('Sheet2');
const shsr=2;//data start row
const rg=sh.getDataRange();//this includes one header row
const dlm='\n';//cell delimiter
let vs=rg.getValues();//this includes header row
let hA=vs.shift();//this put the header row in hA
var ttl={};//converts array indices to column names
var a=0;//added row counter
hA.forEach(function(h,i){ttl[i]=h;});
//vs nolonger contains header row
for(var i=0;i<vs.length;i++) {
var robj={max:1,maxidx:''};
for(var j=0;j<vs[i].length;j++) {
var temp=vs[i][j].toString();
//if data contain line feed then that row will be expanded
if(vs[i][j].toString().indexOf(dlm)!=-1) {
let t=vs[i][j].toString().split(dlm);//split cell on dlm
robj[ttl[j]]=[];//row expansion object
t.forEach(function(e,k){
robj[ttl[j]].push(e);//push expanded cell data into obj property arrays
});
if(robj[ttl[j]].length>robj.max) {
robj.max=robj[ttl[j]].length;//keeping record of the max number of delimited terms
robj.maxidx=j;//never actually used this yet
}
}else{
robj[ttl[j]]=[];
robj[ttl[j]].push(vs[i][j]);//if no dlm the just same the one term
}
}
if(robj.max>1) {
for(var k=0;k<vs[i].length;k++) {
const l=robj[ttl[k]].length;
if(l>1 && l<robj.max) {
for(let m=l;m<robj.max;m++) {
robj[ttl[k]].push(undefined);//This section fills in the cells that had multiple dlms with undefined so that all columns have the same amount of terms in their array
}
}else if(l==1) {
for(let m=1;m<robj.max;m++) {
robj[ttl[k]].push(vs[i][k]);//this section fills in the cells that have no dlms with the same value for all rows
}
}
}
sh.insertRows(i+shsr+1+a, robj.max-1);//insert addtional row
var oA=[];
for(var r=0;r<robj.max;r++) {
oA[r]=[];
for(var k=0;k<vs[i].length;k++) {
oA[r].push(robj[ttl[k]][r]);//This section loads data into the ouput array in preparation for a single setvalues() to load all new rows at one time.
}
}
sh.getRange(i+shsr+a,1,oA.length,oA[0].length).setValues(oA);//load data
a+=robj.max-1;//increment added row counter
}
}
}
动画:
关于javascript - 根据分隔符将 Google Sheets 单元格拆分为多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62718437/