Skip to content

Instantly share code, notes, and snippets.

@jchadwick
Created September 23, 2024 17:32
Show Gist options
  • Save jchadwick/06396e3ea39c0a132a3b0f26bdca43fa to your computer and use it in GitHub Desktop.
Save jchadwick/06396e3ea39c0a132a3b0f26bdca43fa to your computer and use it in GitHub Desktop.
Convert Pennsbury School District rotation day HTML table to Google Calendar CSV import
const fs = require('fs');
const cheerio = require('cheerio');
const path = require('path');
const inputFilePath = path.join(__dirname, 'table.html');
const outputFilePath = path.join(__dirname, 'output.csv');
const DateHeader = 'Date';
const RotationDayHeader = 'Rotation Day';
const { headers, rows } = getTableData(inputFilePath);
const rotationDays = convertTableDataToRotationDays(headers, rows);
const csv = toGoogleCalendarCsv(rotationDays);
//fs.writeFileSync(outputFilePath, csv);
console.log(csv);
function getTableData(inputFilePath) {
const data = fs.readFileSync(inputFilePath, 'utf8')
// Load the HTML into cheerio
const $ = cheerio.load(data);
// Extract table rows
const headers = [];
const rows = [];
$('table tr').each((i, row) => {
$(row).find('th').each((j, cell) => {
headers.push($(cell).text().trim());
});
const cells = [];
$(row).find('td').each((j, cell) => {
cells.push($(cell).text().trim());
});
if (cells.length > 0) {
rows.push(cells);
}
});
return {
headers,
rows
};
}
function convertTableDataToRotationDays(headers, cells) {
const dateIndex = headers.indexOf(DateHeader);
const rotationDayIndex = headers.indexOf(RotationDayHeader);
const rotationDays = cells.map((cell, i) => {
const date = new Date(cell[dateIndex]);
const rotationDay = +cell[rotationDayIndex];
return { date, rotationDay };
});
return rotationDays;
}
function toGoogleCalendarCsv(rotationDays) {
const header = [
"Subject",
"Start Date",
"End Date",
"All Day Event"
].join(',');
const rows = rotationDays.map((day) => {
const date = day.date.toISOString().split('T')[0];
return [
`Rotation Day ${day.rotationDay}`,
date,
date,
'True'
].join(',')
});
return [header, ...rows].join('\n');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment