Fastest way to use Excel with Python to make a table

This is the fastest way to create a table in Excel with Python. We are going to add values to the cells in Excel with openpyxl with the few steps.

The code to use Excel with Python and openpyxl

import os
from openpyxl import Workbook

wb = Workbook()
ws = wb.active

ws.append(["Name","Values","Money"])
ws.append(["Andrew",   10,  10000])
ws.append(["Jane",   11,  12000])

wb.save("file.xlsx")
os.system("file.xlsx")

Example n.2

import os
from openpyxl import Workbook

# This are the data to be written in Excel
data = """
N. Alunno	ITALIANO	STORIA	INGLESE	MATEMATICA 	SCIEN.MOT	FRANCESE	SC.ALIMENT	DIR.TEC.AMM.	LAB.SALA.BAR	RELIGIONE	COMPORTAMENTO	MEDIA	CREDITI	INTEGRAZIONE	TOTALE_CRED.	punti.integraz. Esito
1	Miriam	7	8	6	7	7	7	7	8	7	D	10	7,4	9	1	10	a+c+d+e			AMMESSA
2	Greta	8	7	6	7	6	6	6	7	6	D	8	6,7	8	1	9	a+c+d			AMMESSA
3	Laura	8	8	7	8	8	8	8	9	7	B	10	8,1	10	0	10	>			AMMESSA
""".splitlines()

# Create the Excel file
wb = Workbook()
ws = wb.active # Make the sheet active to be written into

def write_data(data): # data is a multiline string
	"""takes the element of a multiline string and write them in Excel"""
	d2 = []
	[d2.append(d.split()) for d in data]
	[ws.append(d) for d in d2]

# This function writes data in excel from a multiline string
write_data(data)
 
# Save and show the file
wb.save("file2.xlsx")
os.system("file2.xlsx")

 

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.