1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
| import fs from 'fs'; import { google } from 'googleapis';
class GoogleSheetsClient { #spreadsheetId; #credentialsPath; #auth; #sheets;
constructor({ spreadsheetId, credentialsPath = './credentials.json', }) { this.#spreadsheetId = spreadsheetId; this.#credentialsPath = credentialsPath; this.#auth = null; this.#sheets = null; }
async initialize() { try { const credentials = JSON.parse(fs.readFileSync(this.#credentialsPath, 'utf8'));
this.#auth = new google.auth.GoogleAuth({ credentials, scopes: ['https://www.googleapis.com/auth/spreadsheets'], });
this.#sheets = google.sheets({ version: 'v4', auth: this.#auth }); console.log('Google Sheets API authorization successful');
return this; } catch (err) { console.error('Initialization error:', err); throw err; } }
ensureDirectoryExists(dir) { if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); console.log(`Directory created: ${dir}`); } }
async getSheetList() { try { const { data: { sheets } } = await this.#sheets.spreadsheets.get({ spreadsheetId: this.#spreadsheetId, });
return sheets.map(({ properties: { title, sheetId } }) => ({ title, sheetId, })); } catch (err) { console.error('Error fetching worksheet list:', err); throw err; } }
async getSheetData(range) { try { const { data: { values: rows } } = await this.#sheets.spreadsheets.values.get({ spreadsheetId: this.#spreadsheetId, range, });
if (!rows?.length) { console.log('No data found in specified range'); return []; }
return rows; } catch (err) { console.error('Error fetching spreadsheet data:', err); throw err; } }
getEntireSheetData = (sheetName) => this.getSheetData(`${sheetName}!A:Z`);
async updateSheetData(range, values) { try { const result = await this.#sheets.spreadsheets.values.update({ spreadsheetId: this.#spreadsheetId, range, valueInputOption: 'RAW', resource: { values, }, });
console.log(`Updated ${result.data.updatedCells} cells in range "${range}"`); return result.data; } catch (err) { console.error('Error updating spreadsheet data:', err); throw err; } }
async clearAndUpdateSheet(sheetName, values) { try { await this.#sheets.spreadsheets.values.clear({ spreadsheetId: this.#spreadsheetId, range: `${sheetName}!A:Z`, });
return this.updateSheetData(`${sheetName}!A1`, values); } catch (err) { console.error(`Error clearing and updating sheet "${sheetName}":`, err); throw err; } } }
export default GoogleSheetsClient;
|