Files
lifebottle.github.io/gsheets_as_a_database.html
2022-11-27 09:00:29 -05:00

81 lines
3.2 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<title>
Testing data from Google Sheets
</title>
</head>
<body>
<div class="output"></div>
<script>
const sheetID = '1XxiE5T575Twn4enEfwSz1wTnjg6CC71F6b3ZpTzD6xo';
const base = `https://docs.google.com/spreadsheets/d/${sheetID}/gviz/tq?`;
const sheetName = 'Sheet1';
const query = encodeURIComponent('Select *');
const url = `${base}&sheet=${sheetName}&tq=${query}`;
const data = [];
document.addEventListener('DOMContentLoaded', init);
const output = document.querySelector('.output');
function init() {
//console.log('ready');
fetch(url)
.then(res => res.text())
.then(rep => {
//console.log(rep);
const jsData = JSON.parse(rep.substr(47).slice(0, -2));
//console.log(jsData);
const colz = [];
jsData.table.cols.forEach((heading) => {
if (heading.label) {
colz.push(heading.label.toLowerCase().replace(/\s/g, ''));
}
})
jsData.table.rows.forEach((main) => {
//console.log(main);
const row = {};
colz.forEach((ele, ind) => {
//console.log(ele);
row[ele] = (main.c[ind] != null) ? main.c[ind].v : '';
})
data.push(row);
})
maker(data);
})
}
function maker(json) {
const div = document.createElement('div');
div.style.display = 'grid';
output.append(div);
let first = true;
json.forEach((el) => {
//console.log(ele);
const keys = Object.keys(el);
div.style.gridTemplateColumns = `repeat(${keys.length} ,1fr)`;
if (first) {
first = false;
keys.forEach((heading) => {
const ele = document.createElement('div');
ele.textContent = heading.toUpperCase();
ele.style.background = 'black';
ele.style.color = 'white';
div.append(ele);
})
}
keys.forEach((key) => {
const ele = document.createElement('div');
ele.style.border = '1px solid #ddd';
ele.textContent = el[key];
div.append(ele);
})
//console.log(keys);
})
}
</script>
</body>
</html>