-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspreadsheetToJson.js
More file actions
71 lines (57 loc) · 2.32 KB
/
spreadsheetToJson.js
File metadata and controls
71 lines (57 loc) · 2.32 KB
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
const axios = require('axios');
const fs = require('fs');
const path = require('path');
require('dotenv').config();
const SHEET_ID = process.env.GOOGLE_SHEET_ID;
const API_KEY = process.env.GOOGLE_API_KEY;
const OUTPUT_FILE = 'spreadsheet.json';
if (!SHEET_ID || !API_KEY) {
console.error('❌ Missing GOOGLE_SHEET_ID or GOOGLE_API_KEY in .env file');
process.exit(1);
}
async function fetchSheetData(sheetId, apiKey) {
const url = `https://sheets.googleapis.com/v4/spreadsheets/${sheetId}?includeGridData=true&key=${apiKey}`;
try {
const res = await axios.get(url);
const spreadsheet = res.data;
const output = {};
spreadsheet.sheets.forEach(sheet => {
const sheetTitle = sheet.properties.title;
const sheetData = {
rows: [],
charts: []
};
// Extract row data
sheet.data.forEach(grid => {
grid.rowData?.forEach(row => {
const rowValues = row.values?.map(cell => {
if (!cell) return null;
const formula = cell.userEnteredValue?.formulaValue;
const value = cell.formattedValue;
return formula
? { formula, value }
: value || null;
}) || [];
sheetData.rows.push(rowValues);
});
});
// Extract chart data
if (sheet.charts && sheet.charts.length > 0) {
sheet.charts.forEach(chart => {
// You can extract various properties of the chart here
// For simplicity, let's extract chartId and spec (chart type, data, options)
sheetData.charts.push({
chartId: chart.chartId,
spec: chart.spec
});
});
}
output[sheetTitle] = sheetData;
});
fs.writeFileSync(path.resolve(__dirname, OUTPUT_FILE), JSON.stringify(output, null, 2), 'utf-8');
console.log(`✅ Sheet data saved to ${OUTPUT_FILE}`);
} catch (err) {
console.error('❌ Error fetching sheet:', err.response?.data || err.message);
}
}
fetchSheetData(SHEET_ID, API_KEY);