Via a different service, I export a CSV file which I then import into Google Sheets. I then manually clean up the file in order to print out reports.

The issue is, the imported CSV file contains a bunch of columns of data which I do not need. However these columns are never in the same order, so I can't reference the columns by a, b, c, 1, 2, 3, etc. The first row always contains the column headers, so if I can reference the columns by the text in the first row then that would be great.

All I want to do is:

  1. Import CSV
  2. Run Script which deletes all non-required columns so only the columns I need exist.

Currently my import process is:

  1. Go to shared folder in Google Docs
  2. Create new Google Sheet
  3. Import the CSV file
  4. Manually delete all columns and clean up the spreadsheet so I then print it.

I am open to various methods of doing this (even if it makes having a script make a copy of the sheet and only putting the required columns in the new sheet), but would like to avoid having to use a 3rd party add-on or service.


1 Answer 1


Here is a script that deletes all columns except those where the first row is one of the words listed in the "required" variable:

function deleteColumns() {
  var required = ["Name", "Position", "Salary"];

  var sheet = SpreadsheetApp.getActiveSheet();
  var width = sheet.getLastColumn();
  var headers = sheet.getRange(1, 1, 1, width).getValues()[0];
  for (var i = headers.length - 1; i >= 0; i--) {
    if (required.indexOf(headers[i]) == -1) {

The logic is simple: get headers (the data in the first row), and loop over them, deleting whatever is not found in "required" array. There are two things that merit attention:

  1. The deletion process goes from right to left, so that deletion does not change the position of columns that are yet to be processed.
  2. JavaScript arrays are numbered starting with 0, while sheet columns are numbered starting with 1. Hence i+1 in the deleteColumn method.
  • Thank you! It works as intended. Only issue is the script runs a bit slow, at first I didn't think it worked until the browser froze. If it makes a difference, I am running this command on sheets which are around 17,000 rows and 40 columns.
    – Damainman
    Jul 10, 2017 at 3:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.