Skip to content

Commit

Permalink
add export methods
Browse files Browse the repository at this point in the history
  • Loading branch information
Theo Ephraim committed May 14, 2022
1 parent c1d2f23 commit 07b0783
Show file tree
Hide file tree
Showing 5 changed files with 115 additions and 3 deletions.
32 changes: 32 additions & 0 deletions docs/classes/google-spreadsheet-worksheet.md
Original file line number Diff line number Diff line change
Expand Up @@ -312,3 +312,35 @@ Param|Type|Required|Description

?> The authentication method being used must have write access to the destination document as well

### Export

#### `downloadAsCSV(returnStreamInsteadOfBuffer)` (async) :id=fn-downloadAsCSV
> Export worksheet in CSV format
Param|Type|Required|Description
---|---|---|---
`returnStreamInsteadOfBuffer`|Boolean|-|Set to true to return a stream instead of a Buffer

- ↩️ **Returns** - Buffer (or stream) containing CSV data


#### `downloadAsTSV(returnStreamInsteadOfBuffer)` (async) :id=fn-downloadAsTSV
> Export worksheet in TSV format
Param|Type|Required|Description
---|---|---|---
`returnStreamInsteadOfBuffer`|Boolean|-|Set to true to return a stream instead of a Buffer

- ↩️ **Returns** - Buffer (or stream) containing TSV data


#### `downloadAsPDF(returnStreamInsteadOfBuffer)` (async) :id=fn-downloadAsPDF
> Export worksheet in PDF format
Param|Type|Required|Description
---|---|---|---
`returnStreamInsteadOfBuffer`|Boolean|-|Set to true to return a stream instead of a Buffer

- ↩️ **Returns** - Buffer (or stream) containing PDF data


36 changes: 34 additions & 2 deletions docs/classes/google-spreadsheet.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ Property|Type|Description
---|---|---
`spreadsheetId`|String|Document ID<br>_set during initialization, not editable_
`title`|String|Document title
`locale`|String|Document locale/language<br>_ISO code - ex: "en", "en_US"_
`timeZone`|String|Document timezone<br>_CLDR format - ex: "America/New_York", "GMT-07:00"_
`locale`|String|Document locale/language<br>_ISO code - ex: "en", "en\_US"_
`timeZone`|String|Document timezone<br>_CLDR format - ex: "America/New\_York", "GMT-07:00"_
`autoRecalc`|String<br>_enum_|See [RecalculationInterval](https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets#RecalculationInterval)
`defaultFormat`|Object|See [CellFormat](https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/cells#CellFormat)
`spreadsheetTheme`|Object|See [SpreadsheetTheme](https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets#SpreadsheetTheme)
Expand Down Expand Up @@ -210,3 +210,35 @@ Param|Type|Required|Description
`rangeId`|String|✅|ID of the range to remove



### Export

#### `downloadAsHTML(returnStreamInsteadOfBuffer)` (async) :id=fn-downloadAsHTML
> Export entire document in HTML format (zip file)
Param|Type|Required|Description
---|---|---|---
`returnStreamInsteadOfBuffer`|Boolean|-|Set to true to return a stream instead of a Buffer

- ↩️ **Returns** - Buffer (or stream) containing HTML data (in a zip file)


#### `downloadAsXLSX(returnStreamInsteadOfBuffer)` (async) :id=fn-downloadAsXLSX
> Export entire document in XLSX (excel) format
Param|Type|Required|Description
---|---|---|---
`returnStreamInsteadOfBuffer`|Boolean|-|Set to true to return a stream instead of a Buffer

- ↩️ **Returns** - Buffer (or stream) containing XLSX data


#### `downloadAsODS(returnStreamInsteadOfBuffer)` (async) :id=fn-downloadAsODS
> Export entire document in ODS (Open Document Format) format
Param|Type|Required|Description
---|---|---|---
`returnStreamInsteadOfBuffer`|Boolean|-|Set to true to return a stream instead of a Buffer

- ↩️ **Returns** - Buffer (or stream) containing ODS data

39 changes: 39 additions & 0 deletions lib/GoogleSpreadsheet.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ class GoogleSpreadsheet {
this.authMode = null;
this._rawSheets = {};
this._rawProperties = null;
this._spreadsheetUrl = null;

// create an axios instance with sheet root URL and interceptors to handle auth
this.axios = Axios.create({
Expand Down Expand Up @@ -263,6 +264,7 @@ class GoogleSpreadsheet {
...includeCells && { includeGridData: true },
},
});
this._spreadsheetUrl = response.data.spreadsheetUrl;
this._rawProperties = response.data.properties;
_.each(response.data.sheets, (s) => this._updateOrCreateSheet(s));
}
Expand Down Expand Up @@ -382,6 +384,43 @@ class GoogleSpreadsheet {
const { sheets } = result.data;
_.each(sheets, (sheet) => { this._updateOrCreateSheet(sheet); });
}

// EXPORTING /////////////////////////////////////////////////////////////
async _downloadAs(fileType, worksheetId, returnStreamInsteadOfBuffer) {
// see https://stackoverflow.com/questions/11619805/using-the-google-drive-api-to-download-a-spreadsheet-in-csv-format/51235960#51235960

if (['html', 'xlsx', 'ods'].includes(fileType)) {
if (worksheetId) throw new Error(`Cannot specify worksheetId when exporting as ${fileType}`);
} else if (['csv', 'tsv', 'pdf'].includes(fileType)) {
if (worksheetId === undefined) throw new Error(`Must specify worksheetId when exporting as ${fileType}`);
} else {
throw new Error(`unsupported export fileType - ${fileType}`);
}

// google UI shows "html" but passes through "zip"
if (fileType === 'html') fileType = 'zip';

const exportUrl = this._spreadsheetUrl.replace('/edit', '/export');
const response = await this.axios.get(exportUrl, {
baseUrl: '', // unset baseUrl since we're not hitting the normal sheets API
params: {
id: this.spreadsheetId,
format: fileType,
...worksheetId && { gid: worksheetId },
},
responseType: returnStreamInsteadOfBuffer ? 'stream' : 'arraybuffer',
});
return response.data;
}
async downloadAsHTML(returnStreamInsteadOfBuffer = false) {
return this._downloadAs('html', null, returnStreamInsteadOfBuffer);
}
async downloadAsXLSX(returnStreamInsteadOfBuffer = false) {
return this._downloadAs('xlsx', null, returnStreamInsteadOfBuffer);
}
async downloadAsODS(returnStreamInsteadOfBuffer = false) {
return this._downloadAs('ods', null, returnStreamInsteadOfBuffer);
}
}

module.exports = GoogleSpreadsheet;
9 changes: 9 additions & 0 deletions lib/GoogleSpreadsheetWorksheet.js
Original file line number Diff line number Diff line change
Expand Up @@ -864,6 +864,15 @@ class GoogleSpreadsheetWorksheet {
await this._spreadsheet.axios.post(`/values/${this.encodedA1SheetName}:clear`);
this.resetLocalCache(true);
}
async downloadAsCSV(returnStreamInsteadOfBuffer = false) {
return this._spreadsheet._downloadAs('csv', this.sheetId, returnStreamInsteadOfBuffer);
}
async downloadAsTSV(returnStreamInsteadOfBuffer = false) {
return this._spreadsheet._downloadAs('tsv', this.sheetId, returnStreamInsteadOfBuffer);
}
async downloadAsPDF(returnStreamInsteadOfBuffer = false) {
return this._spreadsheet._downloadAs('pdf', this.sheetId, returnStreamInsteadOfBuffer);
}
}

module.exports = GoogleSpreadsheetWorksheet;
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"api",
"googleapis"
],
"homepage": "https://github.com/theoephraim/node-google-spreadsheet",
"homepage": "https://theoephraim.github.io/node-google-spreadsheet",
"repository": {
"type": "git",
"url": "git://github.com/theoephraim/node-google-spreadsheet.git"
Expand Down

0 comments on commit 07b0783

Please sign in to comment.