forked from onescales/google-sheet-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCode.gs
85 lines (71 loc) · 2.35 KB
/
Code.gs
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
// Function to convert sheet data to JSON format
function json(sheetName) {
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
const sheet = spreadsheet.getSheetByName(sheetName);
if (sheet === null) {
return 'Sheet not found';
}
const data = sheet.getDataRange().getValues();
const jsonData = convertToJson(data);
return jsonData;
}
// Function to convert a 2D array to JSON
function convertToJson(data) {
const headers = data[0];
const raw_data = data.slice(1);
let json = [];
raw_data.forEach(d => {
let object = {};
for (let i = 0; i < headers.length; i++) {
object[headers[i]] = d[i];
}
json.push(object);
});
return json;
}
// Function to append a new row to a sheet
function appendRow(sheetName, rowData) {
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
const sheet = spreadsheet.getSheetByName(sheetName);
if (sheet !== null) {
// Read existing data
const existingData = sheet.getRange(1, 1, sheet.getLastRow(), 1).getValues().flat();
// Check if the value already exists
if (existingData.includes(rowData[0])) {
return "Already exists";
}
// Append the new row
sheet.appendRow(rowData);
return "Row added successfully";
}
return "Sheet not found";
}
// Main function to handle GET requests
function doGet(e) {
try {
const path = e.parameter.path;
const action = e.parameter.action;
let debugInfo = `doGet called. Path: ${path}, Action: ${action}`;
if (action === 'read') {
const jsonData = json(path);
return ContentService
.createTextOutput(JSON.stringify({debugInfo, data: jsonData}))
.setMimeType(ContentService.MimeType.JSON);
} else if (action === 'write') {
const rowData = [];
rowData.push(e.parameter['Users'] || '');
const result = appendRow(path, rowData);
return ContentService
.createTextOutput(`${result}. Debug: ${debugInfo}`)
.setMimeType(ContentService.MimeType.TEXT);
} else {
return ContentService
.createTextOutput(`Invalid action. Debug: ${debugInfo}`)
.setMimeType(ContentService.MimeType.TEXT);
}
} catch (error) {
return ContentService
.createTextOutput(`An error occurred: ${error.toString()}`)
.setMimeType(ContentService.MimeType.TEXT);
}
}