Skip to content

Instantly share code, notes, and snippets.

@veev
Created November 3, 2025 17:31
Show Gist options
  • Select an option

  • Save veev/063e9f02d4265e2a763c2923c7336de1 to your computer and use it in GitHub Desktop.

Select an option

Save veev/063e9f02d4265e2a763c2923c7336de1 to your computer and use it in GitHub Desktop.
function unpivotData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = ss.getSheetByName("historical_emissions_GHG_1990_2022"); // Change if your sheet has a different name
var data = sourceSheet.getDataRange().getValues();
// Get headers
var headers = data[0];
var metadataHeaders = headers.slice(0, 6); // A-F columns
var yearHeaders = headers.slice(6); // G onwards
// Create output array
var output = [];
output.push(metadataHeaders.concat(["Year", "Value"])); // New headers
// Process each row
for (var i = 1; i < data.length; i++) {
var row = data[i];
var metadata = row.slice(0, 6);
var values = row.slice(6);
// Create a row for each year
for (var j = 0; j < values.length; j++) {
if (values[j] !== "") { // Skip empty values
output.push(metadata.concat([yearHeaders[j], values[j]]));
}
}
}
// Create new sheet or clear existing one
var outputSheet = ss.getSheetByName("Unpivoted");
if (outputSheet) {
outputSheet.clear();
} else {
outputSheet = ss.insertSheet("Unpivoted");
}
// Write output
outputSheet.getRange(1, 1, output.length, output[0].length).setValues(output);
SpreadsheetApp.getUi().alert("Done! Check the 'Unpivoted' sheet.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment