Created
August 7, 2023 18:20
-
-
Save mvogelgesang/fbc5f9de5f67716841aea263f890d257 to your computer and use it in GitHub Desktop.
A custom function for Google Sheets to turn a spreadsheet range into a Markdown Table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Produced a table in markdown format | |
* | |
* @param {Range} inputRange The range of data to markdown-ify | |
* @param {boolean} includesHeader does the data have a header? defaults to true. | |
* @return {string} Range in markdown table format. | |
* @customfunction | |
*/ | |
function markdownTable(inputRange, includesHeader = true) { | |
let tableOutput = ''; | |
for (row in inputRange) { | |
tableOutput += processTableRow(inputRange[row]) | |
if (includesHeader && row == 0) { | |
tableOutput += markdownHeaderBreak(inputRange[row].length); | |
} | |
} | |
return tableOutput | |
} | |
/** | |
* Produces a pipe (|) delimited string | |
* @param {number} columns The number of columns in the table | |
* @return {string} | |
*/ | |
function markdownHeaderBreak(columns) { | |
let headerBreak = '|'; | |
for (let i = 0; i < columns; i++) { | |
headerBreak += '---|'; | |
} | |
return headerBreak + '\n'; | |
} | |
/** | |
* Wraps a table row in pipes (|) and replaces any line breaks with html <br /> tags | |
* @param {array} row A 1D array of data | |
* @return {string} | |
*/ | |
function processTableRow(row) { | |
let tableRow = '|'; | |
for (column in row) { | |
let colString = String(row[column]); | |
tableRow += colString.replace(/\n/ig, '<br />') + '|'; | |
} | |
return tableRow + '\n'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment