Script to create Markdown table, using Python and Google Spreadsheets 🇺🇸🇪🇸

avatar
(Edited)


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



0
0
0.000
11 comments
avatar

Congratulations @alberto0607! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s):

You received more than 4750 upvotes.
Your next target is to reach 5000 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Check out the last post from @hivebuzz:

Hive Power Up Day - November 1st 2022
Support the HiveBuzz project. Vote for our proposal!
0
0
0.000
avatar

That is pretty cool! Never thought using python for that
!1UP


0
0
0.000
avatar

Python is a very versatile language. Thank you very much for your support

0
0
0.000
avatar
(Edited)

🍕 PIZZA !
@alberto0607! The Hive.Pizza team manually upvoted your post.

I gifted $PIZZA slices here:
curation-cartel tipped alberto0607 (x1)

Learn more at https://hive.pizza!

0
0
0.000
avatar

Hi man, nice work there, I usually use the a website called Table To Markdown for this type of conversion, or I add the markdown code right into the spreadsheet if it is something I need to repeat, but a Python script to go to Markdown is great, especially if you do all calculations in Pandas and then want to make a post from it.

Your script had a few syntax errors, so I corrected them, and also added an input for the file name, one thing to improve would be to create the TXT file in the script and add an input for the file name, plus also use dynamic headers as right now it is locked to the headers used in your file.

import pandas as pd

spreadfile = input("Enter CSV file name: ")

df = pd.read_csv(spreadfile)

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)

Keep up the good work and stay !ALIVE

0
0
0.000
avatar

Thank you very much @flaxz, you have been very nice to me. I will take your code and follow your recommendations. I don't work with Python, but I'm studying it and practicing, I try to do useful things with it.
!CTP

0
0
0.000