Collect data from multiple spreadsheets into one spreadsheet - google-apps-script

I have 184 audit sheets in one folder. I want to reference one cell in each of these sheets and bring them back in to one master spreadsheet.
I have a code that does the opposite that sends a value to each sheet in the folder and changes it to the value that I want. So in essence I want to do the opposite of the script below:
function getdata() {
var files = DriveApp.getFolderById("1gbA2JI1DYNku7SQPaCq1Qk27hnbimPag").getFiles()
while (files.hasNext()) {
var file = files.next();
var shoot = SpreadsheetApp.openById(file.getId());
var sourcesheet = SpreadsheetApp.getActive().getSheetByName("Jan");
var sourcerange = sourcesheet.getRange('A3');
var sourcevalues = sourcerange.getValues();
var destsheet = shoot.getSheetByName('Front Sheet');
var destrange = destsheet.getRange('B5');
destrange.setValues(sourcevalues);
}
}

Your example code doesn't appear to match your explanation but I think I got the basic idea so I made up some of the needed details on my own. I included filenames, ids and 'A3' values. You can choose to modify as needed.
function getdata(month) {
var monthA=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var date=new Date();
var mss=SpreadsheetApp.getActive();
var ms=mss.getSheetByName("Master Sheet");
var vObj={name:[],id:[],value:[]};
var files = DriveApp.getFolderById("1gbA2JI1DYNku7SQPaCq1Qk27hnbimPag").getFilesByType(MimeType.GOOGLE_SHEETS);
while (files.hasNext()) {
var file = files.next();
var fid=file.getId();
var ss = SpreadsheetApp.openById(fid);
var sh = ss.getSheetByName(monthA[date.getMonth()]);
var rg = sh.getRange('A3');
vObj.name.push(file.getName());
vObj.id.push(fid);
vObj.value.push(rg.getValue());
vObj['month']=monthA[date.getMonth()];
}
vObj.id.splice(0,0,'ids');
ms.appendRow(vObj.id);
vObj.name.splice(0,0,vObj.month);
ms.appendRow(vObj.name);
vObj.value.splice(0,0,'values');
ms.appendRow(vObj.value)
}

Related

how to fix my copy data range into other files in app script google

i have to copy my sheet from file1 (16aWONG-TyHYxYFYqfDI7Pw2PVuNvDQ0cnFoIv_SDA4U) into file2 (1zIeqvQuC7RlXy9SB--SaNaEXKT399NvffM3F3nfAXGs)
i have this script, but it didnt work, i don't know where to put fromfile
function getdata() {
var files = DriveApp.getFileById("1zIeqvQuC7RlXy9SB--SaNaEXKT399NvffM3F3nfAXGs").getFiles()
while (files.hasNext()) {
var file = files.next();
var shoot = SpreadsheetApp.openById(file.getId());
var sourcesheet = SpreadsheetApp.getActive().getSheetByName("BahanMix");
var sourcerange = sourcesheet.getRange('A:D');
var sourcevalues = sourcerange.getValues();
var destsheet = shoot.getSheetByName('Sheet23');
var destrange = destsheet.getRange('A:D');
destrange.setValues(sourcevalues);
}
}
I would stick with the spreadsheet app versus using drive as your initial code operates on. I think you can get what you want with this below code. I included a check to ensure the row count is the same.
function getDate() {
var fromFile = SpreadsheetApp.openById("16aWONG-TyHYxYFYqfDI7Pw2PVuNvDQ0cnFoIv_SDA4U");
var targetFile = SpreadsheetApp.openById("1zIeqvQuC7RlXy9SB--SaNaEXKT399NvffM3F3nfAXGs");
var sourcesheet = fromFile.getSheetByName("BahanMix");
var sourcerange = sourcesheet.getRange('A:D');
var sourcevalues = sourcerange.getValues();
var destsheet = targetFile.getSheetByName('Sheet23');
var destrange = destsheet.getRange('A:D');
//make sure the same number or rows exist
if (destsheet.getMaxRows()!= sourcesheet.getMaxRows()){
Browser.msgBox("Row MisMatch. Destination has " +
destsheet.getMaxRows() + " rows while source has " +
sourcesheet.getMaxRows()) + " rows."
}else{
destrange.setValues(sourcevalues);
}
}
Since you are using getActive() your script is bound to your source spreadsheet, so SpreadsheetApp can be used directly to open files.
function getdata() {
var shoot = SpreadsheetApp.openById("1zIeqvQuC7RlXy9SB--SaNaEXKT399NvffM3F3nfAXGs");
var sourcesheet = SpreadsheetApp.getActive().getSheetByName("BahanMix");
var sourcerange = sourcesheet.getRange('A:D');
var sourcevalues = sourcerange.getValues();
var destsheet = shoot.getSheetByName('Sheet23');
var destrange = destsheet.getRange('A:D');
destrange.setValues(sourcevalues);
}

Mass Edit of Cell Range in Sheets in Folder Using Script

I have used this script in the past to edit a cell or range of cells in a set of spreadsheets in a specific folder (using a source file), but when I run the script it does not work. In fact, instead of copying the range from the source sheet it clears out existing data in the destination sheets.
Here is script I have been using:
var files = DriveApp.getFolderById("1NNHFL6fMFz-LwJ4tZrvTN92foXhf7VS8").getFiles()
while (files.hasNext()) {
var file = files.next();
var shoot = SpreadsheetApp.openById(file.getId());
var sourcesheet = SpreadsheetApp.getActive().getSheetByName("Sheet1");
var sourcerange = sourcesheet.getRange('A:A');
var sourcevalues = sourcerange.getFormulas();
var destsheet = shoot.getSheetByName('Sheet1');
var destrange = destsheet.getRange('A:A');
destrange.setValues(sourcevalues);
}
}
Here is a link to the folder I have been testing this in.
Your script works fine if you change setValues() to setFormulas (if you need formulas):
function myFunction() {
var files = DriveApp.getFolderById("1NNHFL6fMFz-LwJ4tZrvTN92foXhf7VS8").getFiles()
while (files.hasNext()) {
var file = files.next();
var shoot = SpreadsheetApp.openById(file.getId());
var sourcesheet = SpreadsheetApp.getActive().getSheetByName("Sheet1");
var sourcerange = sourcesheet.getRange('A:A');
var sourcevalues = sourcerange.getFormulas();
var destsheet = shoot.getSheetByName('Sheet1');
var destrange = destsheet.getRange('A:A');
destrange.setFormulas(sourcevalues); // <------------- HERE
}
}
Try this:
function myfunc() {
var files = DriveApp.getFolderById("1NNHFL6fMFz-LwJ4tZrvTN92foXhf7VS8").getFiles()
const ss=SpreadsheetApp.getActive();
var sourcesheet = ss.getSheetByName("Sheet1");
var sourcerange = sourcesheet.getRange(1,1,sourcesheet.getLastRow(),1);
var sourcevalues = sourcerange.getFormulas();
while (files.hasNext()) {
var file = files.next();
var shoot = SpreadsheetApp.openById(file.getId());
var destsheet = shoot.getSheetByName('Sheet1');
var destrange = destsheet.getRange(1,1,sourcesheet.getLastRow(),1);
destrange.setFormulas(sourcevalues);
}
}

getSheetByName google apps Script returns null

I'm stuck and can't find an answer for my problem.
Here's my current code:
var monthSheet = sourcesheet.getRange('A1').getValue();
var destsheet = shoot.getSheetByName(monthSheet);
monthSheet is String
destsheet is always null and I don't know why...
edit:
function sendAnnouncement() {
var files = DriveApp.getFolderById("xxxxxxxxxxxxxxxxx").getFiles()
while (files.hasNext()) {
var file = files.next();
var shoot = SpreadsheetApp.openById(file.getId());
var sourcesheet = SpreadsheetApp.getActive().getSheetByName("Announcements");
var sourceAnn = sourcesheet.getRange('B2:B2').getValue();
var sourceMonth = sourcesheet.getRange('A2').getValue();
sourcesheet.getRange('A1').setFormula("=VLOOKUP(A2;Settings!B1:C12;2;false)");
var monthSheet = sourcesheet.getRange('A1').getValue();
var sourceTaxStake = sourcesheet.getRange('C2').getValue();
var destsheet = shoot.getSheetByName(monthSheet);
var destTaxStake = destsheet.getRange('H2').getValues();
if ('sourceTaxStake' == "all")
{
var destrange = destsheet.getRange('D8:D8');
destrange.setValues(sourceAnn);
}
else if ('destTaxStake' == 'sourceTaxStake')
{
var destrange = destsheet.getRange('D8:D8');
destrange.setValues(sourceAnn);
}
else
{
}
}
}
Again, that part of code itself is okay. Have you checked what value is monthSheet? Probably it's different from the actual sheet name. Also check its value by Logger.log(monthSheet). Check my example source sheet and destination sheet. Below script is included in the source sheet.
function myFunction() {
var sourcesheet = SpreadsheetApp.getActive().getSheetByName("Announcements");
var monthSheet = sourcesheet.getRange('A1').getValue();
var shoot = SpreadsheetApp.openById('1JxjM7KJRofTRxH5pRpY4vLuY9ojKP__DYjodSIN3rVE');
var destsheet = shoot.getSheetByName(monthSheet);
Logger.log(destsheet.getName()); // dest_s
}
Of course 1JxjM7KJRofTRxH5pRpY4vLuY9ojKP__DYjodSIN3rVE is my destination sheet. And dest_s is the value of Announcements!A1 on the source sheet and, in the same time, the name of sheet on the destination sheet. Check for yourself.
I noticed that sourceTaxStake and destTaxStake had single quotes around them so neither condition would ever by true. I removed the single quotes and the editor immediately darkened them as it does with defined variables.
function sendAnnouncement()
{
var files = DriveApp.getFolderById("xxxxxxxxxxxxxxxxx").getFiles()
while (files.hasNext())
{
var file = files.next();
var shoot = SpreadsheetApp.openById(file.getId());
var sourcesheet = SpreadsheetApp.getActive().getSheetByName("Announcements");
var sourceAnn = sourcesheet.getRange('B2').getValue();
var sourceMonth = sourcesheet.getRange('A2').getValue();
sourcesheet.getRange('A1').setFormula("=VLOOKUP(A2;Settings!B1:C12;2;false)");
var monthSheet = sourcesheet.getRange('A1').getValue();
var sourceTaxStake = sourcesheet.getRange('C2').getValue();
var destsheet = shoot.getSheetByName(monthSheet);
var destTaxStake = destsheet.getRange('H2').getValues();
if (sourceTaxStake == "all")
{
var destrange = destsheet.getRange('D8:D8');
destrange.setValues(sourceAnn);
}
else if (destTaxStake == 'sourceTaxStake')
{
var destrange = destsheet.getRange('D8:D8');
destrange.setValues(sourceAnn);
}
}
}
Thanks for help. There was problem with correct name of the sheet.
I've also removed single quotes from conditions. Everything is working correctly.

Copy value and format from a sheet to a new google Spreadsheet document?

I need to copy a sheet on google SpreadSheet to another SpreadSheet document.
I´ve done my research, and I found two methods that do this, however both have problems that I don´t know how to fix.
The first method copies the sheet with format, but it keeps the referenced cells, so I get a reference error in the new document (#ref). I need a function that copies the format and the values (not references).
function copySheet() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheets()[0];
var destination = SpreadsheetApp.openById("15ucPbZrIYXZAOCYVdpK6OA0oyQT1NcsmuiJmDRfdpHQ");
sheet.copyTo(destination);
}
This second method copies the values without references, however it copies only values, without format.
function copySheetValues()
{
var source = SpreadsheetApp.getActiveSheet();
var sourcename = source.getSheetName();
var sourceDataRange = source.getDataRange();
var sourceSheetValues = sourceDataRange.getValues();
var sourceRows = sourceDataRange.getNumRows();
var sourceColumns = sourceDataRange.getNumColumns();
var destination = SpreadsheetApp.openById('15ucPbZrIYXZAOCYVdpK6OA0oyQT1NcsmuiJmDRfdpHQ');
destination.insertSheet(sourcename, 0);
destination.getDataRange().offset(0, 0, sourceRows, sourceColumns).setValues(sourceSheetValues);
}
How do I write a function that keeps the format and copies the values?
Since you seem to know how to get and set values using the whole data range, just use the other methods to get and set all the other parameters.
The script editor autocomplete is a great help in this case to try not to forget one !
I hope the list is complete, it is a bit of a pain to write though !.
code below, if one of them is not useful to you just delete it (in both directions (set and get).
function copySheetValues(){
var source = SpreadsheetApp.getActiveSheet();
var sourcename = source.getSheetName();
var sValues = source.getDataRange().getValues();
var sBG = source.getDataRange().getBackgrounds();
var sFC = source.getDataRange().getFontColors();
var sFF = source.getDataRange().getFontFamilies();
var sFL = source.getDataRange().getFontLines();
var sFFa = source.getDataRange().getFontFamilies();
var sFSz = source.getDataRange().getFontSizes();
var sFSt = source.getDataRange().getFontStyles();
var sFW = source.getDataRange().getFontWeights();
var sHA = source.getDataRange().getHorizontalAlignments();
var sVA = source.getDataRange().getVerticalAlignments();
var sNF = source.getDataRange().getNumberFormats();
var sWR = source.getDataRange().getWraps();
var destination = SpreadsheetApp.openById('15ucPbZrIYXZAOCYVdpK6OA0oyQT1NcsmuiJmDRfdpHQ');
var destinationSheet = destination.insertSheet(sourcename, 0);
destinationSheet.getRange(1,1,sValues.length,sValues[0].length).setValues(sValues)
.setBackgrounds(sBG)
.setFontColors(sFC)
.setFontFamilies(sFF)
.setFontLines(sFL)
.setFontFamilies(sFFa)
.setFontSizes(sFSz)
.setFontStyles(sFSt)
.setFontWeights(sFW)
.setHorizontalAlignments(sHA)
.setVerticalAlignments(sVA)
.setNumberFormats(sNF)
.setWraps(sWR);
}
Edit :
Bryan's answer and your comment made me think of another solution, much more simple and that handles merged cells as well. Here is the code :
function copySheetValuesV2(){
var source = SpreadsheetApp.getActiveSheet();
var sourceName = source.getSheetName();
var sValues = source.getDataRange().getValues();
var destination = SpreadsheetApp.openById('15ucPbZrIYXZAOCYVdpK6OA0oyQT1NcsmuiJmDRfdpHQ');
source.copyTo(destination)
var destinationSheet = destination.getSheetByName('Copy of '+sourceName)
destinationSheet.getRange(1,1,sValues.length,sValues[0].length).setValues(sValues);// overwrite all formulas that the copyTo preserved
}
In both script be sure that the destination sheet name does not already exist. I didn't handle that case although it is quite easy to do with a try/catch structure.
Another route to try that I think Serge was alluding to here.
function myFunction() {
var source = SpreadsheetApp.openById('SOURCE_ID');
var sourceSheet = source.getSheetByName('Sheet1');
var sourceRange = sourceSheet.getDataRange();
var sourceValues = sourceRange.getValues();
var tempSheet = source.getSheetByName('temp');
var tempRange = tempSheet.getRange('A1');
var destination = SpreadsheetApp.openById('DEST_ID');
sourceRange.copyTo(tempRange); // paste all formats?, broken references
tempRange.offset(0, 0, sourceValues.length, sourceValues[0].length)
.setValues(sourceValues); // paste all values (over broken refs)
tempSheet.copyTo(destination); // now copy temp sheet to another ss
}
This is a variation upon Sergei's answer.
This script will copy all visible sheets and export them in to a new spreadsheet with " Final" appended to the document title.
function copySheetValuesV4(){
var sourceSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheets = sourceSpreadsheet.getSheets();
var destination = SpreadsheetApp.create(sourceSpreadsheet.getName()+' Final');
for (var i = 0; i < sourceSheets.length; i++){
var sourceSheet = sourceSheets[i];
if (!sourceSheet.isSheetHidden()) {
var sourceSheetName = sourceSheet.getSheetName();
var sValues = sourceSheet.getDataRange().getValues();
sourceSheet.copyTo(destination)
var destinationSheet = destination.getSheetByName('Copy of '+sourceSheetName).setName(sourceSheetName);
destinationSheet.getRange(1,1,sValues.length,sValues[0].length).setValues(sValues);// overwrite all formulas that the copyTo preserved */
}
destination.getSheetByName("sheet1").hideSheet() // Remove the default "sheet1" */
}
}

Collect Data from several Spreadsheets and copy it into another sheet

I want to copy data from one spreadsheet into another one. But
1. The Data are on several sheets
2. Only certain Columns (just to speed it up, don't need all columns)
For the beginning I used the following script:
function CopyDataToNewFile() {
var sss = SpreadsheetApp.openById('0AjN7uZG....'); // sss = source spreadsheet
var ss = sss.getSheetByName('Monthly'); // ss = source sheet
//Get full range of data
var SRange = ss.getDataRange();
//get A1 notation identifying the range
var A1Range = SRange.getA1Notation();
//get the data values in range
var SData = SRange.getValues();
var tss = SpreadsheetApp.openById('8AjN7u....'); // tss = target spreadsheet
var ts = tss.getSheetByName('RAWData'); // ts = target sheet
//set the target range to the values of the source data
ts.getRange(A1Range).setValues(SData);
}
I took this one from user2741, which was posted here:
..this one works fine for one sheet.
But now I am unsure how to get the data from more sheets and actually sort it. Does anybody has a good idea on how to do this?
Thank you all,
Sascha
This one here works, if everything happens in the same spreadsheet
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SummarySheet").clear();
mergeSheet2("SummarySheet", "123");
mergeSheet2("SummarySheet", "345");
mergeSheet2("SummarySheet", "748");
mergeSheet2("SummarySheet", "293");
function mergeSheet2(targetSheetName, sourceSheetName) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = ss.getSheetByName(sourceSheetName);
var lastRow = sourceSheet.getLastRow();
var lastCol = sourceSheet.getLastColumn();
var source = sourceSheet.getRange(1,1,lastRow,lastCol); // Error after some iterations: The coordinates or dimensions of the range are invalid. (line 11, file "copy-m.js") -> might be empty spreadsheet
var destSheet = ss.getSheetByName(targetSheetName);
var destRange = destSheet.getRange(destSheet.getLastRow()+1,1);
source.copyTo(destRange, {contentsOnly: true});
}
but for some reason I don't get it run when using different spreadsheets
Error: "Target range and source range must be on the same spreadsheet"
I tried it with:
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SummarySheet").clear();
SpreadsheetApp.openById('ID');
mergeSheet2("SummarySheet", "123");
function mergeSheet2(targetSheetName, sourceSheetName) {
var ss = SpreadsheetApp.openById('ID');
var ssd = SpreadsheetApp.openById('ID');
var sourceSheet = ss.getSheetByName(sourceSheetName);
var lastRow = sourceSheet.getLastRow();
var lastCol = sourceSheet.getLastColumn();
var source = sourceSheet.getRange(1,1,lastRow,lastCol); // Error after some iterations: The coordinates or dimensions of the range are invalid. (line 11, file "copy-m.js") -> might be empty spreadsheet
var destSheet = ssd.getSheetByName(targetSheetName);
var destRange = destSheet.getRange(destSheet.getLastRow()+1,1);
source.copyTo(destRange, {contentsOnly: true});
Any ideas?
The solution is simpler than what you tried, since you want to copy values only and knowing that copyTo only works in the same spreadsheet, just get the values from source and paste it in destination like this:
function copyFromSourceToTarget(targetSheetName, sourceSheetName) {
var ss = SpreadsheetApp.openById('ID');
var ssd = SpreadsheetApp.openById('ID');
var sourceSheet = ss.getSheetByName(sourceSheetName);
var sourceData = sourceSheet.getDataRange().getValues();
var destSheet = ssd.getSheetByName(targetSheetName);
destSheet.getRange(destSheet.getLastRow()+1,1,sourceData.length,sourceData[0].length).setValues(sourceData);
}
To make it more flexible I'd recommend to use 4 parameters and simplify again the code :
function copyFromSourceToTarget(targetSheetName,targetSsId, sourceSheetName,sourceSsId) {
var ss = SpreadsheetApp.openById(sourceSsId)getSheetByName(sourceSheetName);
var ssd = SpreadsheetApp.openById(targetSsId).getSheetByName(targetSheetName);
var sourceData = ss.getDataRange().getValues();
ssd.getRange(ssd.getLastRow()+1,1,sourceData.length,sourceData[0].length).setValues(sourceData);
}