Git Product home page Git Product logo

node-google-spreadsheet's Introduction

google-spreadsheet

The most popular Google Sheets API wrapper for javascript / typescript

NPM version CI status Known Vulnerabilities NPM

  • multiple auth options (via google-auth-library) - service account, OAuth, API key, ADC, etc
  • cell-based API - read, write, bulk-updates, formatting
  • row-based API - read, update, delete (based on the old v3 row-based calls)
  • managing worksheets - add, remove, resize, update properties (ex: title), duplicate to same or other document
  • managing docs - create new doc, delete doc, basic sharing/permissions
  • export - download sheet/docs in various formats

Docs site - Full docs available at https://theoephraim.github.io/node-google-spreadsheet


๐ŸŒˆ Installation - pnpm i google-spreadsheet
(or npm i google-spreadsheet --save or yarn add google-spreadsheet)

Examples

The following examples are meant to give you an idea of just some of the things you can do

IMPORTANT NOTE - To keep the examples concise, I'm calling await at the top level which is not allowed in some older versions of node. If you need to call await in a script at the root level and your environment does not support it, you must instead wrap it in an async function like so:

(async function () {
  await someAsyncFunction();
})();

The Basics

import { GoogleSpreadsheet } from 'google-spreadsheet';
import { JWT } from 'google-auth-library';

// Initialize auth - see https://theoephraim.github.io/node-google-spreadsheet/#/guides/authentication
const serviceAccountAuth = new JWT({
  // env var values here are copied from service account credentials generated by google
  // see "Authentication" section in docs for more info
  email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
  key: process.env.GOOGLE_PRIVATE_KEY,
  scopes: ['https://www.googleapis.com/auth/spreadsheets'],
});

const doc = new GoogleSpreadsheet('<the sheet ID from the url>', serviceAccountAuth);

await doc.loadInfo(); // loads document properties and worksheets
console.log(doc.title);
await doc.updateProperties({ title: 'renamed doc' });

const sheet = doc.sheetsByIndex[0]; // or use `doc.sheetsById[id]` or `doc.sheetsByTitle[title]`
console.log(sheet.title);
console.log(sheet.rowCount);

// adding / removing sheets
const newSheet = await doc.addSheet({ title: 'another sheet' });
await newSheet.delete();

More info:

Working with rows

// if creating a new sheet, you can set the header row
const sheet = await doc.addSheet({ headerValues: ['name', 'email'] });

// append rows
const larryRow = await sheet.addRow({ name: 'Larry Page', email: '[email protected]' });
const moreRows = await sheet.addRows([
  { name: 'Sergey Brin', email: '[email protected]' },
  { name: 'Eric Schmidt', email: '[email protected]' },
]);

// read rows
const rows = await sheet.getRows(); // can pass in { limit, offset }

// read/write row values
console.log(rows[0].get('name')); // 'Larry Page'
rows[1].set('email', '[email protected]'); // update a value
rows[2].assign({ name: 'Sundar Pichai', email: '[email protected]' }); // set multiple values
await rows[2].save(); // save updates on a row
await rows[2].delete(); // delete a row

Row methods support explicit TypeScript types for shape of the data

type UsersRowData = {
  name: string;
  email: string;
  type?: 'admin' | 'user';
};
const userRows = await sheet.getRows<UsersRowData>();

userRows[0].get('name'); // <- TS is happy, knows it will be a string
userRows[0].get('badColumn'); // <- will throw a type error

More info:

Working with cells

await sheet.loadCells('A1:E10'); // loads range of cells into local cache - DOES NOT RETURN THE CELLS
console.log(sheet.cellStats); // total cells, loaded, how many non-empty
const a1 = sheet.getCell(0, 0); // access cells using a zero-based index
const c6 = sheet.getCellByA1('C6'); // or A1 style notation
// access everything about the cell
console.log(a1.value);
console.log(a1.formula);
console.log(a1.formattedValue);
// update the cell contents and formatting
a1.value = 123.456;
c6.formula = '=A1';
a1.textFormat = { bold: true };
c6.note = 'This is a note!';
await sheet.saveUpdatedCells(); // save all updates in one call

More info:

Managing docs and sharing

const auth = new JWT({
  email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
  key: process.env.GOOGLE_PRIVATE_KEY,
  scopes: [
    'https://www.googleapis.com/auth/spreadsheets',
    // note that sharing-related calls require the google drive scope
    'https://www.googleapis.com/auth/drive.file',
  ],
});

// create a new doc
const newDoc = await GoogleSpreadsheet.createNewSpreadsheetDocument(auth, { title: 'new fancy doc' });

// share with specific users, domains, or make public
await newDoc.share('[email protected]');
await newDoc.share('mycorp.com');
await newDoc.setPublicAccessLevel('reader');

// delete doc
await newDoc.delete();

Why?

This module provides an intuitive wrapper around Google's API to simplify common interactions

While Google's v4 sheets API is much easier to use than v3 was, the official googleapis npm module is a giant autogenerated meta-tool that handles every Google product. The module and the API itself are awkward and the docs are pretty terrible, at least to get started.

In what situation should you use Google's API directly?
This module makes trade-offs for simplicity of the interface. Google's API provides a mechanism to make many requests in parallel, so if speed and efficiency are extremely important to your use case, you may want to use their API directly. There are also many lesser-used features of their API that are not implemented here yet.

Support & Contributions

This module was written and is actively maintained by Theo Ephraim.

Are you actively using this module for a commercial project? Want to help support it?
Buy Theo a beer

Sponsors

None yet - get in touch!

Contributing

Contributions are welcome, but please follow the existing conventions, use the linter, add relevant tests, and add relevant documentation.

The docs site is generated using docsify. To preview and run locally so you can make edits, run npm run docs:preview and head to http://localhost:3000 The content lives in markdown files in the docs folder.

License

This is free and unencumbered public domain software. For more info, see https://unlicense.org.

node-google-spreadsheet's People

Contributors

2016rshah avatar agotlieb-sg avatar avimar avatar balupton avatar dependabot[bot] avatar drdrongo avatar frankleonrose avatar gregory avatar hokaccha avatar iros avatar jetersen avatar jw-mcgrath avatar kad3nce avatar korel-san avatar lfdm avatar mandric avatar marcusteh1238 avatar mastef avatar mattfullerton avatar rubenstolk avatar shinout avatar snyk-bot avatar somsy avatar tablekat avatar theoephraim avatar tonyspiro avatar uladkasach avatar usirin avatar yfp avatar zigastrgar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-google-spreadsheet's Issues

Error when trying to read some cells

I was attempting to read some cells with

my_sheet.getCells(1, {"min-row": "1", "min-col": "1", "max-col": "1"}, cb);

and I am getting a strack trace:

22:29:25 web.1  | events.js:85
22:29:25 web.1  |       throw er; // Unhandled 'error' event
22:29:25 web.1  |             ^
22:29:25 web.1  | TypeError: Cannot read property 'substr' of undefined
22:29:25 web.1  |     at new SpreadsheetCell (/Users/buckett/Documents/sakai/sakai-cla-robot/node_modules/google-spreadsheet/index.js:422:36)
22:29:25 web.1  |     at /Users/buckett/Documents/sakai/sakai-cla-robot/node_modules/google-spreadsheet/index.js:292:21
22:29:25 web.1  |     at Array.forEach (native)
22:29:25 web.1  |     at /Users/buckett/Documents/sakai/sakai-cla-robot/node_modules/google-spreadsheet/index.js:291:15
22:29:25 web.1  |     at /Users/buckett/Documents/sakai/sakai-cla-robot/node_modules/google-spreadsheet/index.js:148:15
22:29:25 web.1  |     at Parser.<anonymous> (/Users/buckett/Documents/sakai/sakai-cla-robot/node_modules/xml2js/lib/xml2js.js:484:18)
22:29:25 web.1  |     at Parser.emit (events.js:107:17)
22:29:25 web.1  |     at Object.onclosetag (/Users/buckett/Documents/sakai/sakai-cla-robot/node_modules/xml2js/lib/xml2js.js:445:26)
22:29:25 web.1  |     at emit (/Users/buckett/Documents/sakai/sakai-cla-robot/node_modules/sax/lib/sax.js:639:35)
22:29:25 web.1  |     at emitNode (/Users/buckett/Documents/sakai/sakai-cla-robot/node_modules/sax/lib/sax.js:644:5)
22:29:25 web.1  | exited with code 1

Basically the inputValue on the cell is undefined.

num (max-records) not working without a query

when trying to set the num option on getRows, it fails if there is no query.

It's an issue with the function args and trying to be clever about letting users use the function in different ways.

Authentication recently stopped working

This library worked great for me until a week or so ago, now authentication does not appear to work. This returns an error value which converts to string as [Error: Login failed]. The email / pwd are correct and the sheet key is valid. The sheet is readable without auth if I make it public.

If I inspect the error object, it has a lots of properties including '404' and 'Not Found` which makes me wonder if the Google API it is using might have changed recently?

var GoogleSpreadsheet = require("google-spreadsheet");
var my_sheet = new GoogleSpreadsheet(SPREADSHEET_KEY);
my_sheet.setAuth(GOOGLE_EMAIL, GOOGLE_PWD, function (err, val) {
  if (err) {
    console.log(err); // [Error: Login failed]
    console.log(err.data); //  https://developers.google.com/accounts/docs/AuthForInstalledApps
    console.log(err.response.statusCode); // 404 
    console.log(err.response.statusMessage); // Not Found
    console.log(val); // undefined 
  }
  else console.log("Success");
});

Version 1.1.0 Not on NPM

It looks like the most recent version published to npm is 1.0.1. Would you mind publishing the latest (assuming it's ready, of course)? I'm hoping to take advantage of the bulk cell updates.

Thanks!

OAuth2 token fails with the Auth

I went through the whole Google OAuth2 process to get a refresh and access token. I used the SetAuthKey method and every token seems to fail. I keep getting an invalid token error.

Simply not working

var my_sheet = new GoogleSpreadsheet('1OPx1v-S9-CcJUCJy689UYhbzWupgN_aQdZU4lu9mrBI');
my_sheet.setAuth('[email protected]','111111111', function(err){
my_sheet.getInfo( function( err, sheet_info ){
if(err){
console.error(err);
} else {
sheet_info.worksheets[0].addRow( 2, { colname: 'col value'} ) //here comes Error
}
})
})

throws exception

TypeError: Object.keys called on non-object
at Function.keys (native)
at addRow (/home/zuzel/Documents/node_modules/google-spreadsheet/index.js:98:14)
at addRow (/home/zuzel/Documents/node_modules/google-spreadsheet/index.js:208:17)

Use this in front end

When I used browserify to used this module in front end I encountered this issue.

Uncaught TypeError: fs.readFileSync is not a function. Kindly please show how could I used this in front end.

Best Regards,
Kevin Abestilla

error when running addRows

I'm currently having problems any time I attempt using the addRows functionality.
I've attempted using both forms (using sheet index, and using a sheet instance) of the method without success.
I'm getting a 404 when it attempts to make the remote call.
running the unit tests gives me all passes except for the

  • node_google_spreadsheet - basic_write_and_read
  • node_google_spreadsheet - check_newlines_read
    tests.
    In my code, I'm using an authenticated, private spreadsheet, and I can read and save successfully, but cannot add new rows.

setValue giving Error: options.uri is a required argument

I don't if if I did anything wrong but I can't set a value

cell.setValue("test", function(err) {
      console.log(err);
});

I'm getting options.uri is a required argument

let me know if there is another way to save things. I tried save() but did't work

Add header colnames dinamically

Allow to add more colnames on the header row directly from the API instead of require to do so manually directly on the spreadsheet.

reading another sheet by identifier not index?

is there a way to specify a tab (a sheet within the document) by identifier?

// # is worksheet id - IDs start at 1

since tabs get shifted around it would be better to use the gid param like '1095636746' than a simple left to right ID. I tried to pass that and it currently errors out.

rate limit for the api

This is not an issue related to this module,

Has anyone experienced rate limit problems ?
I have a spreadsheet with around 200 worksheets, I want to bring them all so I iterate the worksheets and do getRows().

I quickly run into

HTTP error 429: Too Many Requests

I can limit the amount of parallel calls, but I am wondering if there's any way to lift this limit.

Thanks for the great lib ๐Ÿ‘

"Error: options.uri is a required argument" when trying to use setValue

var write_sheet = function(col , row , value){
        //convert col and row to single array value
        var sheet_row_length = sheet_info.worksheets[0].colCount;
        var row_value = (row - 1) * sheet_row_length;
        var index = row_value + col;
        spreadsheet.getCells(1, function(err , cell_array){
            cell_array[index].setValue(value, function(err){
                if(err){
                    console.log(err);
                    console.trace();
                }else{
                    console.log("success!");
                }
            })
        });
    };

Is the code I'm using when getting this. The stack trace is as follows

at /Users/joshmcgrath/Documents/Git/spellingbee/app.js:94:29
    at Request._callback (/Users/joshmcgrath/Documents/Git/spellingbee/node_modules/google-spreadsheet/index.js:129:20)
    at self.callback (/Users/joshmcgrath/Documents/Git/spellingbee/node_modules/google-spreadsheet/node_modules/request/request.js:123:22)
    at Request.emit (events.js:95:17)
    at Request.init (/Users/joshmcgrath/Documents/Git/spellingbee/node_modules/google-spreadsheet/node_modules/request/request.js:137:17)
    at new Request (/Users/joshmcgrath/Documents/Git/spellingbee/node_modules/google-spreadsheet/node_modules/request/request.js:99:8)
    at request (/Users/joshmcgrath/Documents/Git/spellingbee/node_modules/google-spreadsheet/node_modules/request/index.js:54:11)
    at async.series.request (/Users/joshmcgrath/Documents/Git/spellingbee/node_modules/google-spreadsheet/index.js:122:9)
    at /Users/joshmcgrath/Documents/Git/spellingbee/node_modules/google-spreadsheet/node_modules/async/lib/async.js:735:13
    at iterate (/Users/joshmcgrath/Documents/Git/spellingbee/node_modules/google-spreadsheet/node_modules/async/lib/async.js:253:13)

Willing to help if you can point me in the right direction.

getRows returns 0

Hi,

Had a look through previous issues and no one seems to be having this issue. getInfo works fine, but no combination of getRows returns anything other than "0" rows. I've looked through the code and console.logged the 'xml' variable that it looks for "entry" in and i get nothing like that in the response.

Any ideas?

thanks

Error: Unexpected close tag

Trying to use getRows to retrieve.

var GoogleSpreadsheet = require('google-spreadsheet');

var mySheet = new GoogleSpreadsheet('1X8c0vyB9syJ12c1Pjwj0RfCwJ4WIcW3VET0ZKDWyTFA');

mySheet.getRows(1, function (err, row_data) {
  if (err) {
    console.error(err);
  } else {
    console.log(row_data);
  }
});

Receiving this error:
[Error: Unexpected close tag Line: 920 Column: 9 Char: >]

Cells with "=IMAGE()" values are returned empty from API and update to row overrides the value

This can be because of the nature of the Google Sheet API but when I use "=IMAGE()" command for a cell, the value is not returned from API. Worse than that, when I try to change and save one other column of the row, since the whole row is saved, the column with "=IMAGE()" is set to empty string.

Possible Suggestions to Solve this Issue:

  • Provide ability for partial updates through save method or so
  • Provide the row number in SpreadsheetRow class so that we can get the related cell through getCells function by giving the min-max values for the row and update the cell individually

Can no longer authenticate with useServiceAccountAuth

So I've been using this lib and a script with no issues for a couple months. Suddenly yesterday when I tried, simply authenticating has started to give me errors.

The code:

DOC.useServiceAccountAuth(CREDENTIALS, (err) => {
    if (err) {
      console.log("Auth error: ", err);
   }
});

The error output:

Auth error: [Error: invalid_grant]

Nothing else is spat out, not sure where to go from here. Is anyone aware of if Google changed anything?

Issue with save method with getRows...

When I call this function, I can delete the row I'm referencing ( del() commented out, but works well), but the save() method on rows[2](presumably on the Spreadsheet Row object here) is not saving my edits on the row's column values. I do see my edits after my reassignments in the console. Have used a service account for access, presumably working with delete capability. Would appreciate help.

var updateSheet = function(){
hotList2.useServiceAccountAuth(creds, function(err){
if(err){
console.log(err);
} else {

        hotList2.getRows(worksheet_id, function( err, rows ){
          if(err){
              console.log(err);
          } else {
          console.log(rows[2]); // accurately reflects target spreadsheet
          rows[2].githubnumber = '3';
          rows[2].submitter = 'Jordan';
          console.log(rows[2]); // can see changes here
          rows[2].save();  // this does not update the spreadsheet
        //   rows[2].del();   // this will work
        }

        });
    }
    });
    };  

getRows fails after empty row

I have a table as follow in Google Docs. There is only a single column and there is a blank row after "fred". All rows after fred are suppressed. : (

users
mike
bob
fred

jeff
john

Attempt to access doc using JWT fails in TypeError

Howdy.

Trying to access a private document using the Service Account method. Have verified that the document is shared with the email address associated with the defined service account.

This is using node v.4.0.0 on OSX. Tried using earlier versions of node to no luck.

Doing so nets me the following error:

/private/var/www/project-name/node_modules/google-spreadsheet/index.js:102
        if (google_auth.expires > +new Date()) return step();
                       ^
TypeError: Cannot read property 'expires' of undefined
    at async.series.auth (/private/var/www/project-name/node_modules/google-spreadsheet/index.js:102:24)
    at /private/var/www/project-name/node_modules/google-spreadsheet/node_modules/async/lib/async.js:689:13
    at iterate (/private/var/www/project-name/node_modules/google-spreadsheet/node_modules/async/lib/async.js:265:13)
    at async.forEachOfSeries.async.eachOfSeries (/private/var/www/project-name/node_modules/google-spreadsheet/node_modules/async/lib/async.js:284:9)
    at _parallel (/private/var/www/project-name/node_modules/google-spreadsheet/node_modules/async/lib/async.js:688:9)
    at Object.async.series (/private/var/www/project-name/node_modules/google-spreadsheet/node_modules/async/lib/async.js:710:9)
    at makeFeedRequest (/private/var/www/project-name/node_modules/google-spreadsheet/index.js:98:11)
    at getInfo (/private/var/www/project-name/node_modules/google-spreadsheet/index.js:157:10)
    at Object.<anonymous> (/private/var/www/project-name/server.js:25:4)
    at Module._compile (module.js:434:26)

Code requesting the spreadsheet is:

AppName.prototype._getGoogDoc           = function() {
    var creds   = this._settings['google-docs']['creds'];
    var gd      = new GoogleSpreadsheet(this._settings['google-docs']['key']);

    gd.useServiceAccountAuth(creds, function(err,sheet_info) {
        if (err) {
            console.log('error', err);
        } else {
            console.log('got it.', sheet_info);
        }

    });
    return gd;
};

Apologies if I'm doing something blatantly wrong here.

documentation for getCells

the way its documented now is super unclear.
here is what opts should look like

{
            'min-row': '3',
            'max-row': '5',
            'min-col': '2',
            'max-col': '4',
            'return-empty': true
}

HTTP error 403: Forbidden "If-Match or If-None-Match header or entry etag attribute required

Hello!

I'm trying to change the value of the cell. However, when I run cell.setValue(newValue) I'm getting the following error:

Unhandled rejection Error: Error: HTTP error 403: Forbidden "If-Match or If-None-Match header or entry etag attribute required"
    at Request._callback (/app/node_modules/google-spreadsheet/index.js:135:20)
    at Request.self.callback (/app/node_modules/google-spreadsheet/node_modules/request/request.js:123:22)
    at emitTwo (events.js:100:13)
    at Request.emit (events.js:185:7)
    at Request.<anonymous> (/app/node_modules/google-spreadsheet/node_modules/request/request.js:877:14)
    at emitOne (events.js:95:20)
    at Request.emit (events.js:182:7)
    at IncomingMessage.<anonymous> (/app/node_modules/google-spreadsheet/node_modules/request/request.js:828:12)
    at emitNone (events.js:85:20)
    at IncomingMessage.emit (events.js:179:7)
    at endReadableNT (_stream_readable.js:906:12)
    at nextTickCallbackWith2Args (node.js:474:9)
    at process._tickDomainCallback (node.js:429:17)
From previous event:
    at /app/api/services/TestService.js:438:25
From previous event:
    at /app/api/services/TestService.js:435:12
    at bound (domain.js:287:14)
    at runBound (domain.js:300:12)
    at processImmediate [as _immediateCallback] (timers.js:383:17)
From previous event:
    at Object.module.exports.testGoogleSpreadsheet (/app/api/services/TestService.js:430:8)
    at Object.bound [as testGoogleSpreadsheet] (/home/user/.nvm/versions/node/v5.5.0/lib/node_modules/sails/node_modules/lodash/dist/lodash.js:729:21)
    at repl:1:13
    at REPLServer.defaultEval (repl.js:254:27)
    at bound (domain.js:287:14)
    at REPLServer.runBound [as eval] (domain.js:300:12)
    at REPLServer.<anonymous> (repl.js:417:12)
    at emitOne (events.js:95:20)
    at REPLServer.emit (events.js:182:7)
    at REPLServer.Interface._onLine (readline.js:211:10)
    at REPLServer.Interface._line (readline.js:550:8)
    at REPLServer.Interface._ttyWrite (readline.js:827:14)
    at ReadStream.onkeypress (readline.js:106:10)
    at emitTwo (events.js:100:13)
    at ReadStream.emit (events.js:185:7)
    at emitKeys (readline.js:1251:14)
    at next (native)
    at ReadStream.onData (readline.js:919:36)
    at emitOne (events.js:90:13)
    at ReadStream.emit (events.js:182:7)
    at readableAddChunk (_stream_readable.js:147:16)
    at ReadStream.Readable.push (_stream_readable.js:111:10)
    at TTY.onread (net.js:523:20)

What could be the reason for this?

Thank you!

getCells options

when i was trying to use optional data like min_row,max_row,return_empty under getCells function .I am not successful doing so.can anyone say me the syntax for using options under getCells function

This is the snippet i tried
my_sheet.getCells(1,{minRows: 2,maxRows: 3,returnEmpty: true},function(err,data) {
console.log(data.length);
// console.log(data);

});

and also i need to read the empty cells inbetween too

How to add first row(header)

I am attempting to create sheets programmatically and that works however adding the data fails with
Error: HTTP error 400: Bad Request "Blank rows cannot be written; use delete instead.

I understand that this is due to needing a column name to add data. Is there a way to initialize a sheet with the first row?

Can hidden worksheets be flagged somehow?

Hi,
Is there any way to flag hidden worksheets? Currently all the worksheets are returned without the possibility to know which ones are hidden and which are not.

Thanks.

Way to clear entire sheet?

I'm working on a node app that reads data from a Mongo database and writes to a Google spreadsheet using this package. The task is going to happen every night. Is there a way to overwrite the rows that were created the previous night? It appears like new rows added using my_sheet.addRows gets added to the bottom.

I was looking into deleting the rows from the previous night but it looks like I can only delete on at a time. Is there a way to delete/clear the entire sheet? Thanks for this package! It's just what I need.

Zach

Set/Get cell color

Hi,

Is there a way to set and get the color of cells/rows within a spreadsheet?

Cheers,
Ash

Can't get a title of sheet

After updating today, 1.1.0, I can't get a title of sheets.

When I call "getInfo", the title of ws_data is undefined.

Could you fix this problem?

Setting value for empty cell

@theoephraim thanks for writing this lib! :)

Is there any way to start working from an empty worksheet with the library? I can't seem to figure out if there's any way to use addRows to set the first row of the worksheet with the column names, or even setting each cell in the first row manually.

I also checked the Google Sheets API docs and couldn't find any methods that would do that.

Only getting 5 rows on public sheet

Per the title, I've got a sheet document with about 150 rows, and I can pull down about 5 of them. On first call to getRows, I pass offset of zero and it pulls down 4 rows. Then I call again with offset of 4 and I get 1 row. Call again with offset of 5 and I get zero rows.

missing & incorrect info in README

in the readme you have this :
options (optional)
start-index - start reading from row #
max-results - max # of rows to read at once
orderby - column key to order by
reverse - reverse results
query - send a structured query for rows (more info)

but its wrong! I've worked out so far that its "start" and "num" instead of "start-index" and "max-results"
I can't get the query to work : providing a link to the google documnetation is all very well, but what kind of entry does the library expect ?

Must I URL-encode my query or is this handled below the hood? Can we have an example or two in readme as a time saver please? thx

Need to migrate to Drive API before April 20, 2015

Google recently communicated that Documents List API will be discontinued on April 20, 2015. This change means that service calls for this API will no longer be supported, and any Google Apps features that are implemented using this API will no longer function.

One of the URL's that will be discontinued is https://spreadsheets.google.com/feeds/ which is used by this module. It's suggested to migrate to the Drive API.

To summarize, node-google-spreadsheet will no longer function as of April 20, 2015 if no action is taken.

google-spreadsheet error: cannot read property of undefined

hi!
i am newer with sailsJs. And now i want to modify a google spreadsheet with nodeJs(using sailsJs). This is my code:

var GoogleSpreadsheet = require("google-spreadsheet");
var my_sheet = new GoogleSpreadsheet('<1Oaxk4rq2W6EhpE0sIP2ZLDcqeBIm-c7RB1Cb5Jyst44>');
/*
var creds = {
client_email: '716006945997-26pdbtn44rnop358e6qn7i8i4ucdbonv@developer.gserviceaccount.com',
private_key: ''
 }
*/
var creds = require('google-generated-creds.json');

my_sheet.useServiceAccountAuth(creds, function(err){
// getInfo returns info about the sheet and an array or "worksheet" objects
my_sheet.getInfo( function( err, sheet_info ){
  if(err)
    res.send(err);
    console.log( sheet_info.title + ' is loaded' );
    // use worksheet object if you want to stop using the # in your calls

    var sheet1 = sheet_info.worksheets[0];
    sheet1.getRows( function( err, rows ){
        rows[0].colname = 'new val';
        rows[0].save(); //async and takes a callback
        rows[0].del();  //async and takes a callback
    });
 });

 // column names are set by google and are based
 // on the header row (first row) of your sheet
my_sheet.addRow( 2, { colname: 'col value'} );

my_sheet.getRows( 2, {
    start: 100,          // start index
    num: 100,              // number of rows to pull
    orderby: 'name'  // column to order results by
 }, function(err, row_data){
    // do something...
  });
  })

But i have this error: Cannot read property 'title' of undefined. Please, is there anyone who can help me to fix my problem? Thanks in advance

getrows() fails when there is an empty row in between

getRows() function returns the array of rows in the spreadsheet. But if there is an empty row in the spreadsheet (for example, take 3rd row as an empty one). then the rows present below (i.e., from 4th row) are not returned by getRows() function.

Error: HTTP error 412: Precondition Failed "Mismatch: etags

Hey,

Using 1.1.3 I'm getting the following error when saving a row for the second time (having waited for the first save to call its callback).

Error: HTTP error 412: Precondition Failed "Mismatch: etags = ["AxNaRiw9OCG7ImA9DEgAGBQ."], version = [1gn9l5sgj227p]"

(I've changed some of the characters above in case any of them were tokens.)

I'm using it to change the text in a cell to "Sending" and then once I've performed the necessary actions I update it to "Sent".

Any ideas?

Thanks!

Luke

Exclude some fields in getRows

Hi,
When executing getRows I see those properties in the object response:
_xml, id, _links, save, del
Is there a way to call getRows and get only the rows under columns?

Thanks.

SpreadsheetRow.content property has gone missing

I just updated from npm yesterday and noticed that my code broke that was using node-google-spreadsheet. I traced the problem down to an undefined object property.

The SpreadsheetRow.content property that was present in v1.0.1 seems to have vanished from 1.1.0 and above. Is this an accident or an intentional API change?

Thanks.

Implement Promise interface

Hello!

Thank you for this great library.

However, it will be much easier to use with Promise interface. I've tried to promisify it using Bluebird, but stumbled upon some weird issues.

useServiceAccountAuth PEM error

I got this error on my local machine (mac os)
[Error: error:0906D06C:PEM routines:PEM_read_bio:no start line]
How can I fix it?

Can't use 'title' as a column heading

We discovered the hard way here okfn/opendatasurvey#473 that any data key called "title" is stripped out when adding a row to a spreadsheet, because of this line:

https://github.com/theoephraim/node-google-spreadsheet/blob/master/index.js#L102

Obviously, this extends to "id" and "content" too.

The removal of these fields is probably because of a perceived clash with these names in the XML format for Spreadsheets, being:

<entry gd:etag='"S0wCTlpIIip7ImA0X0QI"'>
  <id>https://spreadsheets.google.com/feeds/list/key/worksheetId/private/full/rowId</id>
  <updated>2006-11-17T18:23:45.173Z</updated>
  <category scheme="http://schemas.google.com/spreadsheets/2006"
term="http://schemas.google.com/spreadsheets/2006#list"/>
  <title type="text">Bingley</title>
  <content type="text">Hours: 10, Items: 2, IPM: 0.0033</content>
  <link rel="self" type="application/atom+xml"
href="https://spreadsheets.google.com/feeds/list/key/worksheetId/private/full/rowId"/>
 <link rel="edit" type="application/atom+xml"
href="https://spreadsheets.google.com/feeds/list/key/worksheetId/private/full/rowId/version"/>
  <gsx:name>Bingley</gsx:name>
  <gsx:hours>20</gsx:hours>
  <gsx:items>4</gsx:items>
  <gsx:ipm>0.0033</gsx:ipm>
</entry>

But, seeing as spreadsheet data is namespace by 'gsx:' anyway, it is not necessary.

I'll be happy to make a pull request to fix this issue.

rowCount length

Hi there,

Noticing that the rows returned from the worksheet.getRows is different to the value returned from logging the worksheet object.

spreadsheet.useServiceAccountAuth(creds, function (err) {
        // Return the spreadsheet
        spreadsheet.getInfo(function (err, info) {
            // Loop through all the worksheets
            async.eachSeries(info.worksheets, function (worksheet, cb) {

                console.log(worksheet);
                // ... worksheet.rowCount = 49 here ...

                // Loop through the rows
                worksheet.getRows({'max-results': 300}, function (err, rowData) {
                    if (err) return next(err);

                    console.log(rowData.length);
                    // ... rowData.length = 16 here ...

                    cb();
                });
            }, function (err) {
                db.end(function(err) {
                    return next(null, sheetData);
                });
            });
        });
    });

Any thoughts?

getRows not parsing all rows?

The rowCount is 648 but getRows only returns 580. Am i missing something? I expected all my rows to be returned but I only get a subset.

Getting "Spreadsheet key not provided." when I am providing the Key

I am trying to instantiate the spreadsheet object, but I keep getting an error saying I'm not passing a key.

var googleAuth = new GoogleClientLogin( {
    email : '[email protected]',
    password : 'my-hard-to-guess-password',
    service : 'spreadsheets'
} );
var sheet = new GoogleSpreadsheet( "SkQBL762iVNw5Tugtfrgf94tMfTsiZI5KPvEPui6a_P3", googleAuth );

That code gives me the following error:

throw new Error("Spreadsheet key not provided.");

Any ideas?

i want to try

juste un test <a Href="www.google.com"> le lien </a>

spreadsheet add new line

i want to add a new row, between two rows that have already contents.In fact i am adding content to a spreadsheet that is already filled. So i want to shift the rows and and add a new row between two rows that are already filled. Is there anyone who can help me to do this? Thanks

Auth key not working when used with process.env

I have the credentials working from a file, but on heroku the key must not be encoding properly from a provided process.env config via heroku config.

I even tried it locally, and process.env didn't work there either, and then I just pasted in the entire key as if it were coming from the json file and it worked again.

What has worked for other folks?

SpreadsheetCell Class Help

This may not be the appropriate place to post this and if it isn't please direct me to the place that is, but I'm having trouble understanding how I can edit the value of a spreadsheet's cell and from what I can see there seems to be very little documentation on the module as a whole. I'm trying to set the data in one of the spreadsheet's rows to an array, i.e. cell A2 is array[0], B2 is array[1], etc., but the only thing I've been able to do successfully is add rows and I want to be able to do

for (var i = 0; i < rowData[rowData.length - 1].length; i++) {
    spreadsheet.addRow(1, {columnName[i]:rowData[rowData.length - 2][i]});
}

except instead of adding a row with one cell with data like this does, I want to be able to add one row and fill it with all the elements of the last element of rowData[][]. Once again if this is not the appropriate place to post this please let me know and point me to the correct place. Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.