Google Sheets CSV – How to Export Specific Columns as CSV

csvgoogle sheetsgoogle-appsgoogle-apps-script

I have a Google spreadsheet with 10 columns of data. I would like to export columns A, C, E, F as csv. I do not need to export the entire spreadsheet. Can this be done? I do not mind using Google script.

Best Answer

A script cannot give a file to you (well, it could email it to you, but I think this is going too far). You'll need to use "save as csv" menu command, and since it only saves the current sheet, you'll have to create a sheet that has only those columns in it.

The straightforward way is to just create a new sheet and type in cell A1

={'My Sheet'!A:A, 'My Sheet'!C:C, 'My Sheet'!E:F}

If you have to do this often, retyping all this thing with sheet name in every place will get old. This is where a script can be useful. Here is a function that assumed you enter simply

My Sheet,A,C,E,F

into the cell A1, and converts this input into a formula.

function csv() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var data = sheet.getRange(1, 1).getValue().split(',');
  var formula = [];
  for (i = 1; i < data.length; i++) {
    formula.push("'" + data[0] + "'!" + data[i] + ':' + data[i]);
  }
  sheet.getRange(1, 1).setFormula('={' + formula.join(',') + '}');
}