google app script export csv with semicolon instead of comma

4.6k Views Asked by At

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

1

There are 1 best solutions below

0
On BEST ANSWER
  • You want to replace , to ; for the retrieved CSV data.
  • You want to create the replaced data as a file.

If my understanding is correct, how about this answer?

Modification points:

  • The data that ; is used as the delimiter instead of , is no mimeType of text/csv. In this case, it is required to be text/plain.
  • In your script, I would like to propose the following 2 patterns.

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:

  • Please enable V8.

Reference: