Script to create Markdown table, using Python and Google Spreadsheets 馃嚭馃嚫馃嚜馃嚫

Words
754
Reading
4 min
Listen
Play
4y


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

Script to create Markdown table, using Python and Google Spreadshee... | Ecency