# [ Excel Automation Using Python ] [ cheatsheet ]
Workbook Operations:
● Create a new workbook: wb = openpyxl.Workbook()
● Save a workbook: wb.save('workbook.xlsx')
● Open an existing workbook: wb = openpyxl.load_workbook('workbook.xlsx')
● Create a new sheet: ws = wb.create_sheet('Sheet Name')
● Get the active sheet: ws = wb.active
● Get a sheet by name: ws = wb['Sheet Name']
● Get all sheet names: sheet_names = wb.sheetnames
● Remove a sheet: wb.remove(wb['Sheet Name'])
● Copy a sheet: ws_copy = wb.copy_worksheet(wb['Sheet Name'])
● Move a sheet: wb.move_sheet(wb['Sheet Name'], offset=1)
● Rename a sheet: ws.title = 'New Sheet Name'
● Get the sheet dimensions: ws.calculate_dimension()
● Get the number of rows: ws.max_row
● Get the number of columns: ws.max_column
Cell Operations:
● Get a cell value: value = ws['A1'].value
● Set a cell value: ws['A1'] = 'Hello, World!'
● Get a cell formula: formula = ws['A1'].data_type == 'f'
● Set a cell formula: ws['A1'] = '=SUM(B1:B5)'
● Get a cell data type: data_type = ws['A1'].data_type
● Get a cell style: style = ws['A1'].style
● Set a cell style: ws['A1'].style = 'Currency'
● Merge cells: ws.merge_cells('A1:C3')
● Unmerge cells: ws.unmerge_cells('A1:C3')
● Insert a row: ws.insert_rows(1)
● Delete a row: ws.delete_rows(1)
● Insert a column: ws.insert_cols(1)
● Delete a column: ws.delete_cols(1)
Range Operations:
● Get a range of cells: cell_range = ws['A1:C3']
By: Waleed Mousa
● Get the values of a range: values = [cell.value for row in ws['A1:C3']
for cell in row]
● Set the values of a range: for row in ws['A1:C3']: for cell in row:
cell.value = 'Value'
● Get the row of a cell: row = ws['A1'].row
● Get the column of a cell: column = ws['A1'].column
● Get the coordinate of a cell: coordinate = ws['A1'].coordinate
● Get the cell using row and column: cell = ws.cell(row=1, column=1)
● Get the rows in a range: rows = tuple(ws.iter_rows(min_row=1, max_row=3,
min_col=1, max_col=3))
● Get the columns in a range: columns = tuple(ws.iter_cols(min_row=1,
max_row=3, min_col=1, max_col=3))
Data Manipulation:
● Apply a formula to a range: for row in ws.iter_rows(min_row=1, max_row=3,
min_col=1, max_col=3): for cell in row: cell.value = '=SUM(A1:A3)'
● Fill a range with values: for row in ws['A1:C3']: for cell in row:
cell.value = 'Value'
● Transpose a range: ws['D1:F3'] = list(zip(*ws['A1:C3']))
● Sort a range: ws.sort_values(by='A', range_string='A1:C3')
● Filter a range: ws.auto_filter.ref = 'A1:C3'
● Apply conditional formatting: ws.conditional_formatting.add('A1:C3',
rule)
● Pivot data: ws._pivots.append(pivot)
● Group rows or columns: ws.row_dimensions.group(1, 3, hidden=True)
● Ungroup rows or columns: ws.row_dimensions.ungroup(1, 3)
Chart Operations:
● Create a chart: chart = openpyxl.chart.BarChart()
● Add data to a chart: chart.add_data(ws['A1:C3'])
● Set the chart title: chart.title = 'Chart Title'
● Set the chart axes titles: chart.x_axis.title = 'X-Axis';
chart.y_axis.title = 'Y-Axis'
● Set the chart legend: chart.legend.position = 'r'
● Add the chart to a sheet: ws.add_chart(chart, 'E5')
● Create a line chart: chart = openpyxl.chart.LineChart()
● Create a pie chart: chart = openpyxl.chart.PieChart()
● Create a scatter chart: chart = openpyxl.chart.ScatterChart()
By: Waleed Mousa
● Create a bubble chart: chart = openpyxl.chart.BubbleChart()
● Create a radar chart: chart = openpyxl.chart.RadarChart()
Formatting Operations:
● Set the font: ws['A1'].font = openpyxl.styles.Font(name='Arial', size=12,
bold=True)
● Set the alignment: ws['A1'].alignment =
openpyxl.styles.Alignment(horizontal='center', vertical='center')
● Set the border: ws['A1'].border =
openpyxl.styles.Border(left=Side(style='thin'), right=Side(style='thin'),
top=Side(style='thin'), bottom=Side(style='thin'))
● Set the fill: ws['A1'].fill =
openpyxl.styles.PatternFill(start_color='00FF0000', end_color='00FF0000',
fill_type='solid')
● Set the number format: ws['A1'].number_format = '#,##0.00'
● Set the row height: ws.row_dimensions[1].height = 20
● Set the column width: ws.column_dimensions['A'].width = 15
● Set the cell protection: ws['A1'].protection =
openpyxl.styles.Protection(locked=True, hidden=False)
● Apply a named style: ws['A1'].style = 'Named Style'
● Create a named style: named_style =
openpyxl.styles.NamedStyle(name='Named Style', font=Font(bold=True))
Data Validation:
● Add a data validation: ws.data_validation('A1', validation)
● Add a list validation: validation =
openpyxl.worksheet.datavalidation.DataValidation(type='list',
formula1='"Value1,Value2,Value3"')
● Add a whole number validation: validation =
openpyxl.worksheet.datavalidation.DataValidation(type='whole',
operator='between', formula1='1', formula2='10')
● Add a decimal validation: validation =
openpyxl.worksheet.datavalidation.DataValidation(type='decimal',
operator='greaterThan', formula1='0')
● Add a date validation: validation =
openpyxl.worksheet.datavalidation.DataValidation(type='date',
operator='between', formula1='2023-01-01', formula2='2023-12-31')
By: Waleed Mousa
● Add a time validation: validation =
openpyxl.worksheet.datavalidation.DataValidation(type='time',
operator='lessThan', formula1='12:00')
● Add a text length validation: validation =
openpyxl.worksheet.datavalidation.DataValidation(type='textLength',
operator='lessThanOrEqual', formula1='255')
● Add a custom validation: validation =
openpyxl.worksheet.datavalidation.DataValidation(type='custom',
formula1='=A1>0')
Conditional Formatting:
● Add a conditional formatting rule: ws.conditional_formatting.add('A1:C3',
rule)
● Add a cell is rule: rule =
openpyxl.formatting.rule.CellIsRule(operator='greaterThan',
formula=['10'], fill=PatternFill(bgColor='00FF0000'))
● Add a color scale rule: rule =
openpyxl.formatting.rule.ColorScaleRule(start_type='min',
start_color='00FF0000', end_type='max', end_color='0000FF00')
● Add a data bar rule: rule =
openpyxl.formatting.rule.DataBarRule(start_type='min', end_type='max',
color='00FF0000')
● Add an icon set rule: rule =
openpyxl.formatting.rule.IconSetRule('3Arrows', 'percent', [10, 20, 30])
● Add a top/bottom rule: rule = openpyxl.formatting.rule.Top10Rule(rank=10,
percent=True)
● Add an average rule: rule =
openpyxl.formatting.rule.AverageRule(aboveAverage=True,
fill=PatternFill(bgColor='00FF0000'))
● Add a unique/duplicate rule: rule =
openpyxl.formatting.rule.DuplicateValuesRule(style='uniqueValues',
fill=PatternFill(bgColor='00FF0000'))
● Add a text contains rule: rule =
openpyxl.formatting.rule.TextComparisonRule(operator='containsText',
formula=['Text'], fill=PatternFill(bgColor='00FF0000'))
Table Operations:
● Create a table: table =
openpyxl.worksheet.table.Table(displayName='Table1', ref='A1:C3')
● Add a table to a sheet: ws.add_table(table)
By: Waleed Mousa
● Get a table by name: table = ws.tables['Table1']
● Get the table data: table_data = ws[table.ref]
● Add a row to a table: ws.append(['Value1', 'Value2', 'Value3'])
● Delete a row from a table: ws.delete_rows(table.ref.rows[-1])
● Add a column to a table:
table.tableColumns.append(openpyxl.worksheet.table.TableColumn(name='New
Column'))
● Delete a column from a table: table.tableColumns.pop(1)
● Apply a table style: table.tableStyleInfo =
openpyxl.worksheet.table.TableStyleInfo(name='TableStyleMedium2',
showFirstColumn=False, showLastColumn=True, showRowStripes=True,
showColumnStripes=False)
● Refresh a table: ws.tables['Table1'].ref = 'A1:D4'
File Operations:
● Create a new Excel file: wb = openpyxl.Workbook();
wb.save('new_file.xlsx')
● Open an existing Excel file: wb =
openpyxl.load_workbook('existing_file.xlsx')
● Save a workbook as a new file: wb.save('new_file.xlsx')
● Save a workbook as a template: wb.template = True;
wb.save('template.xltx')
● Save a workbook as a macro-enabled file: wb.save('macro_file.xlsm',
as_template=True)
● Create a PDF file: ws.sheet_view.pageLayoutView = True;
wb.save('file.pdf')
● Create an HTML file: wb.save('file.html')
● Create a CSV file: csv_writer = csv.writer(open('file.csv', 'w'));
csv_writer.writerows(ws.values)
● Create a TSV file: tsv_writer = csv.writer(open('file.tsv', 'w'),
delimiter='\t'); tsv_writer.writerows(ws.values)
● Create an ODS file: wb.save('file.ods')
Pivot Table Operations:
● Create a pivot table: pivot = openpyxl.pivot.PivotTable(cacheId=1,
dataOnRows=True, dataOnCols=False, dataRef=ws['A1:C10'],
outlineData=True, rowGrandTotals=True, colGrandTotals=True)
● Add a pivot table to a sheet: ws._pivots.append(pivot)
● Set the pivot table fields: pivot.fields = ['Field1', 'Field2', 'Field3']
By: Waleed Mousa
● Set the pivot table row fields: pivot.rowFields = ['Field1']
● Set the pivot table column fields: pivot.colFields = ['Field2']
● Set the pivot table data fields: pivot.dataFields =
[openpyxl.pivot.DataField('Field3', 'Sum', '=SUM(%s)')]
● Set the pivot table style: pivot.style = 'PivotStyleMedium4'
● Filter a pivot table: pivot.filters =
[openpyxl.pivot.PivotFilter('Field1', ['Value1', 'Value2'])]
● Refresh a pivot table: pivot.cache.refreshOnLoad = True
● Set the pivot table layout: pivot.colGrandTotals = False;
pivot.outlineData = False
● Add a calculated field: pivot.calculatedFields =
[openpyxl.pivot.CalculatedField('Calculated Field', '=Field1/Field2')]
Data Validation Advanced:
● Add a list validation with a formula: validation =
openpyxl.worksheet.datavalidation.DataValidation(type='list',
formula1='=Sheet1!$A$1:$A$10')
● Add a custom validation with a message: validation =
openpyxl.worksheet.datavalidation.DataValidation(type='custom',
formula1='=A1>0', errorStyle='stop', errorTitle='Invalid Value',
error='Value must be greater than 0')
● Add a validation with a drop-down list: validation =
openpyxl.worksheet.datavalidation.DataValidation(type='list',
formula1='"Option 1,Option 2,Option 3"', allowBlank=True,
showDropDown=True, showInputMessage=True, promptTitle='Select an option',
prompt='Please select an option from the drop-down list')
● Add a validation with a dynamic formula: validation =
openpyxl.worksheet.datavalidation.DataValidation(type='list',
formula1='=OFFSET(Sheet1!$A$1,0,0,COUNTA(Sheet1!$A:$A),1)')
● Add a validation with a named range: validation =
openpyxl.worksheet.datavalidation.DataValidation(type='list',
formula1='=MyNamedRange')
● Remove data validation from a cell: ws['A1'].data_validation = None
● Remove data validation from a range: for cell in ws['A1:C3']:
cell.data_validation = None
Named Ranges and Formulas:
● Create a named range: ws.create_named_range('MyRange', ws['A1:C3'])
● Get a named range: named_range = ws.get_named_range('MyRange')
By: Waleed Mousa
● Delete a named range: ws.remove_named_range('MyRange')
● Get all named ranges: named_ranges = wb.get_named_ranges()
● Create a named formula: ws.create_named_formula('MyFormula',
'=SUM(A1:A10)')
● Get a named formula: named_formula = ws.get_named_formula('MyFormula')
● Delete a named formula: ws.remove_named_formula('MyFormula')
● Get all named formulas: named_formulas = wb.get_named_formulas()
Conditional Formatting Advanced:
● Add a conditional formatting rule with a formula: rule =
openpyxl.formatting.rule.Rule(type='expression', formula=['=$A1>10'],
fill=PatternFill(bgColor='00FF0000'))
● Add a conditional formatting rule with multiple conditions: rule =
openpyxl.formatting.rule.Rule(type='expression',
formula=['AND($A1>10,$B1<20)'], fill=PatternFill(bgColor='00FF0000'))
● Add a conditional formatting rule with a custom formula: rule =
openpyxl.formatting.rule.Rule(type='expression',
formula=['=ISODD(ROW())'], fill=PatternFill(bgColor='00FF0000'))
● Add a conditional formatting rule with a named range: rule =
openpyxl.formatting.rule.Rule(type='expression', formula=['=MyRange'],
fill=PatternFill(bgColor='00FF0000'))
● Add a conditional formatting rule with a data bar: rule =
openpyxl.formatting.rule.DataBarRule(start_type='num', start_value=0,
end_type='num', end_value=100, color="FF0000", showValue=True,
minLength=0, maxLength=100)
● Add a conditional formatting rule with an icon set: rule =
openpyxl.formatting.rule.IconSetRule('5Rating', 'percent', [0, 20, 40,
60, 80], showValue=True, reverse=True)
● Remove conditional formatting from a cell: ws['A1'].formatting = []
● Remove conditional formatting from a range: for cell in ws['A1:C3']:
cell.formatting = []
Chart Advanced:
● Add a series to a chart:
chart.series.append(openpyxl.chart.Series(values=ws['B1:B10'],
title='Series Title'))
● Set the chart axis options: chart.x_axis.title = 'X-Axis';
chart.y_axis.title = 'Y-Axis'; chart.x_axis.scaling.min = 0;
chart.y_axis.scaling.max = 100
By: Waleed Mousa
● Set the chart legend options: chart.legend.position = 'r';
chart.legend.fontName = 'Arial'; chart.legend.fontSize = 12
● Set the chart title options: chart.title.text = 'Chart Title';
chart.title.fontName = 'Arial'; chart.title.fontSize = 16
● Set the chart data labels: chart.dataLabels =
openpyxl.chart.DataLabelList(showVal=True, showPercent=True,
fontName='Arial', fontSize=10)
● Set the chart plot area: chart.plotArea.layoutTarget =
openpyxl.chart.layout.Layout.FACTOR
● Add a trendline to a chart: chart.trendlines =
[openpyxl.chart.Trendline(spPr=openpyxl.chart.GraphicalProperties(solidFi
ll='00FF0000'))]
● Add a data table to a chart: chart.dataTable =
openpyxl.chart.DataTable(showHorzBorder=True, showVertBorder=True,
showOutline=True)
● Add a second axis to a chart: chart.secondaryAxis =
openpyxl.chart.axis.NumericAxis(axId=200, tickLblPos='low', crossAx=100)
● Combine multiple charts: chart1 + chart2
Workbook Protection:
● Protect a workbook: wb.security =
openpyxl.workbook.protection.WorkbookProtection(workbookPassword='passwor
d', lockStructure=True, lockWindows=True)
● Unprotect a workbook: wb.security =
openpyxl.workbook.protection.WorkbookProtection()
● Protect a sheet: ws.protection =
openpyxl.worksheet.protection.SheetProtection(sheet=True, objects=True,
scenarios=True, formatCells=True, formatColumns=True, formatRows=True,
insertColumns=True, insertRows=True, insertHyperlinks=True,
deleteColumns=True, deleteRows=True, selectLockedCells=True,
selectUnlockedCells=True, password='password')
● Unprotect a sheet: ws.protection =
openpyxl.worksheet.protection.SheetProtection()
Worksheet Views:
● Set the zoom level: ws.sheet_view.zoomScale = 150
● Set the grid lines visibility: ws.sheet_view.showGridLines = False
● Set the row and column headers visibility:
ws.sheet_view.showRowColHeaders = False
By: Waleed Mousa
● Set the freeze panes: ws.sheet_view.pane =
openpyxl.worksheet.pane.Pane(xSplit=3, ySplit=2, topLeftCell='D3',
activePane='bottomRight', state='frozen')
● Set the selected cell: ws.sheet_view.selection[0].activeCell = 'A1';
ws.sheet_view.selection[0].sqref = 'A1:C3'
● Set the page layout view: ws.sheet_view.pageLayoutView = True
Data Manipulation Advanced:
● Apply a formula to a column: for cell in ws['D']: cell.value =
'=SUM(A{0}:C{0})'.format(cell.row)
● Apply a formula to a row: for cell in ws[10]: cell.value =
'=SUM({0}1:{0}9)'.format(cell.column_letter)
● Apply a formula to a range with variables: for row in ws['A1:C3']: for
cell in row: cell.value = '=SUM(A1:A{0})'.format(row[0].row)
● Transpose a range with formulas: for row, col in zip(ws['A1:C3'],
ws['D1:F3']): for cell, value in zip(row, col): cell.value = value.value
● Sort a range by multiple columns: ws.sort_values(by=['A', 'B'],
range_string='A1:C10', ascending=[True, False])
● Filter a range by multiple conditions: ws.auto_filter.ref = 'A1:C10';
ws.auto_filter.add_filter_column(0, ['Value1', 'Value2']);
ws.auto_filter.add_filter_column(1, ['Value3', 'Value4'])
● Create a summary table with formulas: ws['D1'] = 'Total'; ws['D2'] =
'=SUM(B2:B10)'; ws['E1'] = 'Average'; ws['E2'] = '=AVERAGE(B2:B10)'
Hyperlinks and External Data:
● Add a hyperlink to a cell: ws['A1'].hyperlink =
openpyxl.worksheet.hyperlink.Hyperlink(ref='A1',
target='https://www.example.com')
● Add a hyperlink to a range: for cell in ws['A1:C3']: cell.hyperlink =
openpyxl.worksheet.hyperlink.Hyperlink(ref=cell.coordinate,
target='https://www.example.com')
● Remove hyperlinks from a cell: ws['A1'].hyperlink = None
● Remove hyperlinks from a range: for cell in ws['A1:C3']: cell.hyperlink =
None
● Import data from a CSV file: wb = openpyxl.Workbook(); ws = wb.active;
with open('data.csv', 'r') as file: reader = csv.reader(file); for row in
reader: ws.append(row)
● Import data from a JSON file: wb = openpyxl.Workbook(); ws = wb.active;
with open('data.json', 'r') as file: data = json.load(file); for row in
data: ws.append(row)
By: Waleed Mousa
● Import data from a database: wb = openpyxl.Workbook(); ws = wb.active;
connection = pyodbc.connect('DRIVER={SQL
Server};SERVER=server_name;DATABASE=database_name;UID=username;PWD=passwo
rd'); cursor = connection.cursor(); cursor.execute('SELECT * FROM
table_name'); for row in cursor.fetchall(): ws.append(row)
● Import data from a web API: wb = openpyxl.Workbook(); ws = wb.active;
response = requests.get('https://api.example.com/data'); data =
response.json(); for row in data: ws.append(row)
Macros and VBA:
● Enable macros in a workbook: wb.vba_project =
openpyxl.workbook.vba_project.VbaProject()
● Add a macro to a workbook: module = wb.vba_project.add_module('Module1');
module.code = 'Sub Macro1()\nMsgBox "Hello, World!"\nEnd Sub'
● Run a macro: wb.vba_project.run('Module1.Macro1')
● Delete a macro: wb.vba_project.remove_module('Module1')
● Add a user-defined function (UDF): module =
wb.vba_project.add_module('Module1'); module.code = 'Function
MyFunction(x As Double) As Double\nMyFunction = x * 2\nEnd Function'
● Use a UDF in a formula: ws['A1'] = '=MyFunction(10)'
By: Waleed Mousa