Update: I wrote for loops to fix the merged cell and column width issues. Just need some help with the borders!
I'm working on copying a range of cells from one Google Spreadsheet to another Google Spreadsheet. The difficult part is that I'm trying to keep ALL formatting. I have been able to preserve all of the formatting thus far, except for 3 items: cell borders, various merged cells, and column width. Any help would be greatly appreciated. Sorry in advance, just found out about Google App Script yesterday and I've never used JS before.
function importTable() {
// Source spreadsheet
var srcSpreadSheet = SpreadsheetApp.openById("SpreadSheet-ID");
var scrSheet = srcSpreadSheet.setActiveSheet(srcSpreadSheet.getSheetByName("Sheet1"));
// Destination spreadsheet
var destSpreadSheet = SpreadsheetApp.openById("SpreadSheet-ID");
var destSheet = destSpreadSheet.setActiveSheet(destSpreadSheet.getSheetByName("Test"));
destSheet.clear();
// Get data and formatting from the source sheet
var range = scrSheet.getRange(1, 2, 24, 16);
var values = range.getValues();
var background = range.getBackgrounds();
var banding = range.getBandings();
var mergedRanges = range.getMergedRanges();
var fontColor = range.getFontColors();
var fontFamily = range.getFontFamilies();
var fontLine = range.getFontLines();
var fontSize = range.getFontSizes();
var fontStyle = range.getFontStyles();
var fontWeight = range.getFontWeights();
var horAlign = range.getHorizontalAlignments();
var textStyle = range.getTextStyles();
var vertAlign = range.getVerticalAlignments();
// Put data and formatting in the destination sheet
var destRange = destSheet.getRange(1, 2, 24, 16);
destRange.setValues(values);
destRange.setBackgrounds(background);
destRange.setFontColors(fontColor);
destRange.setFontFamilies(fontFamily);
destRange.setFontLines(fontLine);
destRange.setFontSizes(fontSize);
destRange.setFontStyles(fontStyle);
destRange.setFontWeights(fontWeight);
destRange.setHorizontalAlignments(horAlign);
destRange.setTextStyles(textStyle);
destRange.setVerticalAlignments(vertAlign);
// Iterate through to put merged ranges in place
for (var i = 0; i < mergedRanges.length; i++) {
destSheet.getRange(mergedRanges[i].getA1Notation()).merge();
}
// Iterate through to get the column width of the source destination
for (var i = 1; i < 18; i++) {
var width = scrSheet.getColumnWidth(i);
destSheet.setColumnWidth(i, width);
}
// Iterate through to get the row heighth of the source destination
for (var i = 1; i < 27; i++){
var height = scrSheet.getRowHeight(i);
destSheet.setRowHeight(i, height);
}
}
How about this workaround? In this workaround, copyTo() of Class Sheet and copyTo() of Class Range are used. I think that there are several answers for your situation. So please think of this as one of them.
The flow of this script is as follows.
Sample script :
Note :
SpreadSheet-ID
.References :
If I misunderstand your question, please tell me. I would like to modify it.