English
Markdown tables are one of the easiest ways to present data or lists in our publications, either in our Hive blog or in any website. From the need to present a table created in Google Spreadsheets that contained a list of users and data for each of them, and that was growing with the passing of the days, I began to investigate how to create a script that could take this list of data and send it formatted in Markdown to a text file, and not having to transcribe everything, which is tedious and can lead to errors.
I managed to create a very simple script with the Python programming language and its Pandas library, which I explain below.
First we need to create the table in Google Spreadsheets, see here.
Then we need to get the public link to this spreadsheet in .csv format.
Now we create two files, one called main.py and one called list.txt, the first one is going to contain our Python script and the second one is going to give us the table in Markdown format ready to copy and paste.
Then we import the Pandas library and we get the data and we get the data with the function "read_csv", we save it in a variable and we print on screen the obtained dataframe.
import pandas as pd
df = pd.read_csv('spreadsheat_link')
spreadsheet_table = df
print(spreadsheet_table)
Output:
Now we need a function that opens the list.txt file with read and write permissions, adds the table header, saves and closes the file.
def main():
new_route = 'list.txt'.
save_file = open(new_route, 'r+')
table_header = '''| COLUMN_1 | COLUMN_2 | COLUMN_3 |
| ----- | ----- | ----- |\n'''
save_file.write(table_header)
save_file.close()
main()
Output:
Now we go with the last step, we send as parameter to the previous function, the variable that contains the dataframe and with a for loop, we will iterate the dataframe and each row data we add it in a variable, that will allow us to create the string that will be added formatted in the list.txt file.
import pandas as pd
df = pd.read_csv('spreadsheat_link')
spreadsheet_table = df
print(spreadsheet_table)
def main(dspreadsheet_table):
imp_spreadsheet_table = spreadsheet_table
new_route = 'list.txt
save_file = open(new_route, 'r+')
table_header = '''| COLUMN_1 | COLUMN_2 | COLUMN_3 |
| ----- | ----- | ----- |\n'''
save_file.write(table_header)
for i, file in imp_spreadsheet_table.iterrows():
column_1 = file['column_1']
column_2 = file['column_2']]
column_3 = file['column_3']]
table_data = f'| | {column_1} | {column_2} | {column_3} |'
save_file.write(table_data)
save_file.close()
main(spreadsheet_table)
Output:
We already have the table formatted in Markdown code ready to copy and paste wherever we want, avoiding transcription errors and less work time.
I share this script with you so that it can be tested and improved, if you have any comments or want to share another implementation of the code, I will be happy to receive them. Best regards.
Translated with www.DeepL.com/Translator (free version)
Español
Las tablas en Markdown es una de las formas más sencillas de presentar datos o listas en nuestras publicaciones, tanto en nuestro blog de Hive o en cualquier sitio web. A partir de la necesidad de presentar una tabla creada en Google Spreadsheets que contenía una lista de usuarios y datos de cada uno de ellos, y que iba creciendo con el pasar de los días, comencé a investigar la forma de crear script pudiera tomar esta lista de datos y enviarla formateada en Markdown a un archivo de texto, y no tener que transcribir todo, lo cual es tedioso y puede conllevar a errores.
Logré crear un script muy sencillo con el lenguaje de programación Python y su librería Pandas, el cual explico a continuación.
Primero hay que crear la tabla en Google Spreadsheets, ver aquí.
Luego necesitamos obtener el enlace público de esta hoja de spreadsheets en formato .csv.
Ahora creamos dos archivos, uno llamado main.py y otro list.txt, el primero va a contener nuestro script de Python y el segundo nos va a entregar la tabla en formato Markdown listo para copiar y pegar.
A continuación importamos la librería Pandas y nos traemos los datos y traemos los datos con la función "read_csv", lo guardamos en una variable e imprimimos en pantalla el dataframe obtenido.
import pandas as pd
df = pd.read_csv('spreadsheat_link')
spreadsheet_table = df
print(spreadsheet_table)
Salida:
Ahora necesitamos una función que abra el archivo list.txt con permisos de lectura y escritura, agregue el encabezado de la tabla, guarde y la cierre el archivo.
def main():
new_route = 'list.txt'
save_file = open(new_route, 'r+')
table_header = '''| COLUMN_1 | COLUMN_2 | COLUMN_3 |
| ----- | ----- | ----- |\n'''
save_file.write(table_header)
save_file.close()
main()
Salida:
Ahora vamos con el último paso, enviamos como parámetro a la función anterior, la variable que contiene el dataframe y con un bucle for, vamos iterar el dataframe y cada dato de la fila lo agregamos en un variable, que nos permitirá crear el string que se agregará formateado en el archivo list.txt.
import pandas as pd
df = pd.read_csv('spreadsheat_link')
spreadsheet_table = df
print(spreadsheet_table)
def main(dspreadsheet_table):
imp_spreadsheet_table = spreadsheet_table
new_route = 'list.txt'
save_file = open(new_route, 'r+')
table_header = '''| COLUMN_1 | COLUMN_2 | COLUMN_3 |
| ----- | ----- | ----- |\n'''
save_file.write(table_header)
for i, file in imp_spreadsheet_table.iterrows():
column_1 = file['column_1']
column_2 = file['column_2']
column_3 = file['column_3']
table_data = f'| {column_1} | {column_2} | {column_3} |\n'
save_file.write(table_data)
save_file.close()
main(spreadsheet_table)
Salida:
Ya tenemos lista la tabla formateada en código Markdown para copiar y pegar donde deseemos, evitando errores de transcripción y menor tiempo de trabajo.
Comparto este script con ustedes para que pueda ser probado y mejorado, si tiene algún comentario o desea compartir otra implementación del código,estaré encantado de recibirlo. Un abrazo.
Images are my own or screenshots taken by me, unless outside sources are indicated.
Discord: alberto0607#6813
Follow me on: Twitter