Switches and more...

Thursday, June 4, 2020

Excel Spreadsheet Manipulation with ord() and chr() in Python

import openpyxl, os
from openpyxl.styles import Font
from openpyxl.styles.colors import Color

'''
 Adapted from https://automatetheboringstuff.com/2e/chapter13/
 Data files used can be found at this link

 Formulas
 ========
 Excel formulas can configure cells to contain values calculated from other cells.

 >>> sheet['B9'] = '=SUM(B1:B8)'
 This will store =SUM(B1:B8) as the value in cell B9.

'''

os.chdir('/Google Drive/python_work/MyPythonScripts/datafiles')
print(os.getcwd())

wb = openpyxl.Workbook() # creates a WB with a single default sheet called 'Sheet'
wb.create_sheet(index=0, title='S1')
wb.create_sheet(index=1, title='S2')
wb.create_sheet(index=2, title='S3')
# Deleting default worksheet
try:
    del wb['Sheet']
    print('Removed Worksheet "Sheet"')
except KeyError:
    print('Worksheet "Sheet" does not exist')
print(wb.sheetnames)

myFont = Font(name='Arial', color='FF0000', size=14, bold=True)

# Set sheet 'S3' as active worksheet
wb.active = wb['S3']
print(wb.active)
# Manipulate sheet 'S3'
sheet = wb.active
sheet['A1'] = 200
sheet['A2'] = 300
# Set the formula.
sheet['A3'] = '=SUM(A1:A2)'
print(sheet['A3'].value)

# Set sheet 'S2' as active worksheet
wb.active = wb['S2']
print(wb.active)
sheet = wb.active
'''
# Set the Area's cell values using two for loops:
# The outer for goes over each row in the slice;
#   The nested for loop goes through each cell in that row,
#    sets the font to myFont
#    and sets the value to val
'''
for row in sheet['A1':'C4']:
    val = 0
    alpha = ord('A')
    chr(alpha)
    for cell in row:
        val += 1
        cell.value = val
        cell.font = myFont
'''
Sets the row segment (Area A5 to C5) to the sum of the cells in its column
ord('A') returns the ascii integer value for 'A' --> 65
chr(65) returns character value for ascii integer value 65 --> 'A'
Set alpha in the loop to increment by 1 and then use chr(alpha) to move from
column A to B to C. This loop accomplishes the same task as doing this:

 sheet['A5'] = '=SUM(A1:A4)'
 sheet['B5'] = '=SUM(B1:B4)'
 sheet['C5'] = '=SUM(C1:C4)'
'''
number = 5
i = 0
for row in sheet['A5':'C5']:
    for cell in row:
        alpha = ord('A') + i
        alphaNum = '%s%s' %(chr(alpha), number)
        print('%s   %s   %s' %(alphaNum, alpha, i))
        sheet[alphaNum] = '=SUM(%s1:%s4)' %(chr(alpha), chr(alpha))
        i += 1


wb.save('formulas.xlsx')
wb.close() 

No comments:

Post a Comment

Please add comments so I may update the material to accommodate platform modification to various commands. Also if you have some real-world caveats, do please share.