google-apps-scriptautomatic-semicolon-insertion

google app script export csv with semicolon instead of comma


I am using the code below to export a google spreadsheet to CSV in a specific folder. I need to have a semicolon (;) as delimiter instead of a comma (,)

function saveAsCSV() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssname = ss.getName();
var sheet = ss.getActiveSheet();
var parentFolder = DriveApp.getFolderById("MyID");
var folder = parentFolder;
var curDate = Utilities.formatDate(new Date(), "GMT+1", "yyyyMMdd")

var fileName = "MyName" + curDate + ".csv";
var url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/export? 
exportFormat=csv&format=csv";  
var token = ScriptApp.getOAuthToken();  
var response = UrlFetchApp.fetch(url + sheet.getSheetId(), {
headers: {
  'Authorization': 'Bearer ' +  token
}
});
folder.createFile(response.getBlob().setName(fileName));
}

Thank you for your help


Solution

  • If my understanding is correct, how about this answer?

    Modification points:

    Pattern 1:

    In this pattern, the values are retrieved and the data separated by ; is created.

    Modified script:

    When your script is modified please modify as follows.

    From:

    var url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/export? 
    exportFormat=csv&format=csv";  
    var token = ScriptApp.getOAuthToken();  
    var response = UrlFetchApp.fetch(url + sheet.getSheetId(), {
    headers: {
      'Authorization': 'Bearer ' +  token
    }
    });
    folder.createFile(response.getBlob().setName(fileName));
    

    To:

    var values = sheet.getDataRange().getValues();
    var outputData = values.map(r => r.join(";")).join("\n");
    folder.createFile(fileName, outputData, MimeType.PLAIN_TEXT);
    

    Pattern 2:

    In this pattern, the retrieved CSV data is converted.

    Modified script:

    When your script is modified please modify as follows.

    From:

    folder.createFile(response.getBlob().setName(fileName));
    

    To:

    var csvData = Utilities.parseCsv(response.getBlob().getDataAsString());
    var outputData = csvData.map(r => r.join(";")).join("\n");
    folder.createFile(fileName, outputData, MimeType.PLAIN_TEXT);
    

    Note:

    Reference: