I commented out my attempt as it keeps failing… any thoughts?
// script to be run on below noted folder and output to second specified folder in same drive
// converts spreadsheets to TXT files
function convertSpreadsheetsToDocs() {
const mainFolderName = "Test Spreadsheets"; // Replace with your main folder name
const subFolderName = "Subfolder5"; // Replace with your subfolder name
const mainFolder = DriveApp.getFoldersByName(mainFolderName).next();
const subFolder = mainFolder.createFolder(subFolderName); // Create a subfolder
const spreadsheets = mainFolder.getFilesByType(MimeType.GOOGLE_SHEETS);
while (spreadsheets.hasNext()) {
const spreadsheet = spreadsheets.next();
const spreadsheetName = spreadsheet.getName();
const docName = spreadsheetName + " (Converted)";
const doc = DocumentApp.create(docName);
const sheet = SpreadsheetApp.openById(spreadsheet.getId()).getActiveSheet();
const dataRange = sheet.getDataRange();
const values = dataRange.getValues();
dataRange.setNumberFormat("@"); // Set cell format as plain text
let text = values.map(row => row.join("t")).join("n"); // Convert data to tab-delimited text
// Replace carriage return with page break
text = text.replace(/n/g, "nn");
// Replace tab with carriage return
text = text.replace(/t/g, "n");
const blob = Utilities.newBlob(text, MimeType.PLAIN_TEXT);
// const blob = Utilities.newBlob(text, MimeType.GOOGLE_DOCS);
const docFile = subFolder.createFile(blob.setName(docName + ".txt"));
// File.setContentType(MimeType.GOOGLE_DOCS);
DriveApp.getFileById(doc.getId()).setTrashed(true); // Delete the temporary Google Doc
}
Logger.log("Spreadsheets converted to text file successfully.");
}
I can create the .txt file from a spreadsheet but fail when trying to make it a google doc. In the end I need to add some formatting… remove the first five or so lines and tag a font to it to make it pretty
2
Answers
Here's what worked and note above in comment back to Miguel, has an error but it runs so I'm running with it.
Based on this and this, it does not seem
createFile
is able to create files of theGoogle Docs
mime type.As an alternative, you can create a new (blank) doc file (via the
DocumentApp
or advancedDrive
API), and then append elements from the spreadsheet to that document. Depending on how you want things formatted in the final product, this could be quite tedious, but in the simplest case you could do something like so: