OPENPYXL
Published at Oct 4, 2021The new publishing experience is out! 🎉 Try it by duplicating this notebook and creating an app or continue with the current editor until the auto-transition on October 31, 2023.
Practica de excel con openpyxl
Requirement already satisfied: openpyxl in /root/venv/lib/python3.7/site-packages (3.0.9)
Requirement already satisfied: et-xmlfile in /root/venv/lib/python3.7/site-packages (from openpyxl) (1.1.0)
import numpy as np
import openpyxl as xl
from openpyxl.styles import colors
from openpyxl.styles import Color, PatternFill, Font, Border
from openpyxl.styles.differential import DifferentialStyle
from openpyxl.formatting.rule import ColorScaleRule, CellIsRule, FormulaRule
from openpyxl.worksheet.datavalidation import DataValidation
1. Crear la siguiente lista de numpy : N estudiantes. Codigos 1, 2, 3, ..., N.
N = 40
codes = np.arange(1, N+1)
np.random.seed(0)
2. Dos columnas de notas. Columna 1 y columna 2 : numeros aleatorios normal, promedio 3.5, sigma 0.5
grades1 = np.random.normal(3.5, 0.5, N)
grades2 = np.random.normal(3.1, 0.8, N)
3. Abrir un nuevo archivo de excel - workbook
wb = xl.Workbook()
sheet = wb.active
4. Escribir cada una de estas columnas (colocando el titulo en negrita, size = 15). Usar iter_rows
sheet['A1'] = "Codigos"
sheet['A1'].font = Font(color="8700FF", size=15, bold=True)
for ii in range(1, N+1):
sheet['A'+str(ii+1)] = codes[ii-1]
sheet['B1'] = "Notas Quiz"
sheet['B1'].font = Font(color="00B6FF", size=15, bold=True)
for jj in range(1, N+1):
sheet['B'+str(jj+1)] = grades1[jj-1]
sheet['C1'] = "Notas Parcial"
sheet['C1'].font = Font(color="FF8000", size=15, bold=True)
for kk in range(1, N+1):
sheet['C'+str(kk+1)] = grades2[kk-1]
5. Definitiva : promedio usando formula de excel
sheet['D1'] = "Definitiva"
sheet['D1'].font = Font(color="1ED634", size=15, bold=True)
for mm in range(1, N+1):
ineed=sheet['B'+str(mm+1)]
ineed2=sheet['C'+str(mm+1)]
sheet['D'+str(mm+1)] ='=AVERAGE(B%s:C%s)' % (mm+1,mm+1)
sheet['F1'] = "Promedio Curso Nota 1"
sheet['F1'].font = Font(size=15, bold=True)
sheet['G1'] ='=AVERAGE(B2:B41)'
sheet['F3'] = "Promedio Curso Nota 2"
sheet['F3'].font = Font(size=15, bold=True)
sheet['G3'] ='=AVERAGE(C2:C41)'
6. Añadir formato condicional a la definitiva para marcar las notas menores a 3.0 (estilo que ustedes escojan. Ver https://openpyxl.readthedocs.io/en/stable/formatting.html)
redFill = PatternFill(start_color='EE1111', end_color='EE1111',fill_type='solid')
sheet.conditional_formatting.add('D2:D41',CellIsRule(operator='lessThan', formula=['3.0'], stopIfTrue=True, fill=redFill))
7. Incluya una figura de las notas definitivas por estudiante (https://openpyxl.readthedocs.io/en/stable/charts/introduction.html)
from openpyxl.chart import BarChart, Reference, Series
values = Reference(sheet, min_col=1 , min_row=1 , max_col=4 , max_row=40 )
chart = BarChart()
chart.add_data(values)
sheet.add_chart(chart, "F15")
8. Añada un autofiltro a las columnas para poderlas procesar después en excel (https://openpyxl.readthedocs.io/en/stable/filters.html)
sheet.auto_filter.ref = "A1:D41"
sheet.auto_filter.add_sort_condition("B2:B41")
9. A cada columna de notas añada una validación de datos para que las notas sean siempre mayores a 0.0 y menores a 5.0 (https://openpyxl.readthedocs.io/en/stable/validation.html)
dv = DataValidation(type="decimal", operator="between", formula1=0.0, formula2=5.0)
dv.error ='Introduce una entrada válida'
dv.errorTitle = 'Invalid Entry'
dv.add('B2:C41')
sheet.add_data_validation(dv)
10. Incluya al final la columna de definitivas, en tres filas,la nota mínima, la nota máxima y el promedio. Deben usar fórmulas de excel.
sheet['D43'] = "MIN curso DEFINITIVA"
sheet['D43'].font = Font(size=15, bold=True)
sheet['E43'] = "=MIN(D2:D41)"
sheet['D44'] = "MAX curso DEFINITIVA"
sheet['D44'].font = Font(size=15, bold=True)
sheet['E44'] = "=MAX(D2:D41)"
sheet['D45'] = "Promedio Curso DEFINITIVA"
sheet['D45'].font = Font(size=15, bold=True)
sheet['E45'] ='=AVERAGE(D2:D41)'
11. Guardar el archivo en excel y comprobar que todo está como se espera.