完全不熟悉编码,我需要将行转换为Google脚本中的一列作为函数(不是公式)
Depending on the project their can be 100 columns and where I need to start the un-pivot from can vary so in a different project Column "X" instead of Column "C" in the below example
我已经搜索了几个小时,但没有找到任何可行的方法。
编辑:更好的例子
数据看起来像
A1 A2 A3 A4 A5 A6 A7
a1 b1 c1 d1 e1 f1 g1
a2 b2 c2 d2 e2 f2 g2
a3 b3 c3 d3 e3 f3 g3
a4 b4 c4 d4 e4 f4 g4
需要
A1 A2 A3 New New1
a1 b1 c1 A4 d1
a1 b1 c1 A5 e1
a1 b1 c1 A6 f1
a1 b1 c1 A7 g1
a2 b2 c2 A4 d2
a2 b2 c2 A5 e2
a2 b2 c2 A6 f2
a2 b2 c2 A7 g2
a3 b3 c3 A4 d3
a3 b3 c3 A5 e3
a3 b3 c3 A6 f3
a3 b3 c3 A7 g3
a4 b4 c4 A4 d4
a4 b4 c4 A5 e4
a4 b4 c4 A6 f4
我发现了这一点,看起来很有希望: How do you create a "reverse pivot" in Google Sheets?
提前感谢您的帮助
function transformData(){
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();//read whole sheet
var output = [];
var headers = data.shift();// get headers
var empty = headers.shift();//remove empty cell on the left
var products = [];
for(var d in data){
var p = data[d].shift();//get product names in first column of each row
products.push(p);//store
}
Logger.log('headers = '+headers);
Logger.log('products = '+products);
Logger.log('data only ='+data);
for(var h in headers){
for(var p in products){ // iterate with 2 loops (headers and products)
var row = [];
row.push(headers[h]);
row.push(products[p]);
row.push(data[p][h])
output.push(row);//collect data in separate rows in output array
}
}
Logger.log('output array = '+output);
sheet.getRange(sheet.getLastRow()+1,1,output.length,output[0].length)
.setValues(output);
}
答案 0 :(得分:0)
以下示例脚本如何?
function transformData(){
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
var header = data[0].slice(3, 5);
var newHeader = [data[0][0], data[0][1], "New", "New1"];
data.shift();
var output = [];
output.push(newHeader);
for(var i in data) {
for (var j=0; j<newHeader.length-2; j++) {
var temp = [];
temp.push(data[i][0], data[i][1], header[j], data[i][j + 3]);
output.push(temp);
}
}
sheet.getRange(sheet.getLastRow()+1,1,output.length,output[0].length).setValues(output);
}
var newHeader = [data[0][0], data[0][1], "New", "New1"]
。如果我误解了你的问题,请告诉我。我想修改。
function transformData(){
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
var header = data[0].slice(-4);
var newHeader = [data[0][0], data[0][1], data[0][2], "New", "New1"];
data.shift();
var output = [];
output.push(newHeader);
for(var i in data) {
for (var j=0; j<4; j++) {
var temp = [];
temp.push(data[i][0], data[i][1], data[i][2], header[j], data[i][j + 3]);
output.push(temp);
}
}
sheet.getRange(sheet.getLastRow()+1,1,output.length,output[0].length).setValues(output);
}