19

I can't find any reference to an API that enables Rest API clients to export an existing Google Sheet to a csv file.

https://developers.google.com/sheets/

I believe there should be a way to export them.

4

5 回答 5

27

The following URL gives you the CSV of a Google spreadsheet per sheet. The sheet must be accessible by the public, by anyone with the link (unlisted).

The parameters you need to provide are:

  • sheet ID (that is simply the ID in the URL of a Google Spreadsheet https://docs.google.com/spreadsheets/d/{{ID}}/edit)
  • sheet name (that is simply the name of the sheet as given by the user)
https://docs.google.com/spreadsheets/d/{{ID}}/gviz/tq?tqx=out:csv&sheet={{sheet_name}}

With that URL you can run a GET-request to fetch the CSV. Or paste it in your browser address bar.

于 2020-04-08T18:06:50.413 回答
9

You can use the Drive API to do this today -- see https://developers.google.com/drive/v3/web/manage-downloads#downloading_google_documents, however that will limit you to the first sheet of the document. The Sheets API doesn't expose exporting as CSV today, but may offer it in the future.

于 2016-06-08T18:30:21.947 回答
6

Firstly you should make document accessible for anyone. Then you get url. From this url you should extract long id composed from big and small letters and numbers. Then use this script.

#!/bin/bash

long_id="id_assigned_to_your_document"
g_id="number_assigned_to_card_in_google_sheet"

wget --output-document=temp.csv "https://docs.google.com/spreadsheets/d/$long_id/export?gid=$g_id&format=csv&id=$long_id"

If you use only one card in document, their number is: g_id="0"

The problem you will probably have is connected with strange spaces in obtained file. I use this second script to process it

#!/bin/bash
#Delete all lines beginning with a # from a file
#http://stackoverflow.com/questions/8206280/delete-all-lines-beginning-with-a-from-a-file
sed '/^#/ d' temp.csv | 
# reomve spaces
# http://stackoverflow.com/questions/9953448/how-to-remove-all-white-spaces-from-a-given-text-file
tr -d "[:blank:]" |
# regexp "1,2" into 1.2
# http://www.funtoo.org/Sed_by_Example,_Part_2
sed 's/\"\([−]\?[0-9]*\),\([0-9]*\)\"/\1.\2/g' > out.csv

Update

As Sam mentioned, api is better solution. There is now great documentation on address:

https://developers.google.com/sheets/quickstart/php

With example that generate output having CSV structure.

于 2016-06-08T14:53:26.757 回答
6

Nobody's mentioned gspread yet, so here's how I did it:

#open sheet
sheet = gc.open_by_key(sheet_id)

#select worksheet
worksheet = sheet.get_worksheet(0)

#download values into a dataframe
df = pd.DataFrame(worksheet.get_all_records())

#save dataframe as a csv, using the spreadsheet name
filename = sheet.title + '.csv'
df.to_csv(filename, index=False)
于 2020-06-04T23:32:27.847 回答
1

If you don't have easy access to or familiarity with PHP, here's a very barebones Google Apps Script Web App that once deployed and the caller permission accepted, should allow clients with an appropriately scoped access token or api key to export an existing Google Sheet to a csv file. It takes a Google Sheets spreadsheet id and sheet name (and optional download filename) as query parameters, and returns the corresponding theoretically RFC 4180 compliant CSV file.

Further instructions on deploying an Apps Script project as a web app are here: https://developers.google.com/apps-script/guides/web#deploying_a_script_as_a_web_app.

You can deploy it and test it out easily in the browser just by visiting the "Current web app URL" (as provided when you publish as web app from the script editor), and accepting the consent screen, or even just visit the one that I deployed (configured to execute as the accessing user, and unverified/scary consent) at the example URL.

The tricky part (as usual) is getting the OAuth token or API key set up, but if you're already calling the Google Sheets V4 API, you've probably already got that dialed in. I used CURL to make sure that it behaved as a REST api, but the technique I used to get an OAuth token there is both a distraction and frankly a little scary to include here since it's really easy to mess up. If you don't already have a way to get one, that's probably a good topic for a separate SO question in any case.

One related (and big!) caveat: I'm not 100% sure how the consent and verification interact with a pure Rest client (i.e. how that works if you DON'T visit this in the browser first...), and/or whether this script would need to be in the same GCP project as the other code that uses the Sheets API. If there's interest, and/or it doesn't work right out of the box, please let me know and I'll happily dig deeper and follow up.

// Example URL, assuming:
// "Current web app URL": https://script.google.com/a/tillerhq.com/macros/s/AKfycbyZlWAW6bpCpnFoPjbdjznDomFRbTNluG4siCBMgOy2qU2AGoA/exec
// spreadsheetId: 1xNDWJXOekpBBV2hPseQwCRR8Qs4LcLOcSLDadVqDA0E
// sheet name: Sheet1
// (optional) filename: mycsv.csv
//
// https://script.google.com/a/tillerhq.com/macros/s/AKfycbyZlWAW6bpCpnFoPjbdjznDomFRbTNluG4siCBMgOy2qU2AGoA/exec?spreadsheetid=1xNDWJXOekpBBV2hPseQwCRR8Qs4LcLOcSLDadVqDA0E&sheetname=Sheet1&filename=mycsv.csv?spreadsheetid=1xNDWJXOekpBBV2hPseQwCRR8Qs4LcLOcSLDadVqDA0E&sheetname=Sheet1&filename=mycsv.csv
//


var REQUIRED_PARAMS = [
  'spreadsheetid', // example: "1xNDWJXOekpBBV2hPseQwCRR8Qs4LcLOcSLDadVqDA0E"
  'sheetname'      // Case-sensitive; example: "Sheet1"
];

// Returns an RFC 4180 compliant CSV for the specified sheet in the specified spreadsheet
function doGet(e) {

  REQUIRED_PARAMS.forEach(function(requiredParam) {
    if (!e.parameters[requiredParam]) throw new Error('Missing required parameter ' + requiredParam);
  });

  var spreadsheet = SpreadsheetApp.openById(e.parameters.spreadsheetid);
  var sheet = spreadsheet.getSheetByName(e.parameters.sheetname);
  if (!sheet) throw new Error("Could not find sheet " + e.parameters.sheetname + " in spreadsheet " + e.parameters.spreadsheetid);

  var filename = e.parameters.filename || (spreadsheet.getName() + "_" + e.parameters.sheetname + ".csv");


  var numRows = sheet.getLastRow();
  var numColumns = sheet.getLastColumn();

  var values = sheet.getSheetValues(1, 1, numRows, numColumns);

  function quote(s) {

    s = s.toString();

    if ((s.indexOf("\r") == -1)
       && (s.indexOf("\n") == -1)
       && (s.indexOf(",") == -1)
       && (s.indexOf("\"") == -1)) return s;

    // Fields containing line breaks (CRLF)*, double quotes, and commas should be enclosed in double-quotes;
    // anything other than that we already returned, so if we get here -- escape it and quote it.

    // *That's what the text of the RFC says, but the ABNF (...and Excel) treat EITHER CR or LF as requiring quotes.

    // Replace any double quote with a double double quote, and wrap the whole thing in quotes
    return "\"" + s.replace(/"/g, '""') + "\"";
  };

  var csv = values.map(function(row) {
    return row.map(quote).join();
  }).join("\r\n") + "\r\n";


  return ContentService
  .createTextOutput(csv)
  .setMimeType(ContentService.MimeType.CSV)
  .downloadAsFile(filename);
}
于 2018-03-01T05:37:46.587 回答