Automating Excel In Python

Hey Python Programmer In this Post I will Show you How can automate Excel Work Using openpyxl ..

openpyxl ?

openpyxl is a python module used to work on excel using python.

Installation

> pip install openpyxl

Hit this command in your window Command Prompt or terminal

Now Come to the next step that is usage of the openpyxl

Write a workbook

from openpyxl import Workbook
from openpyxl.utils import get_column_letter

wb = Workbook()

dest_filename = 'empty_book.xlsx'

ws1 = wb.active
ws1.title = "range names"

for row in range(1, 40):
ws1.append(range(600))

ws2 = wb.create_sheet(title="Pi")

ws2['F5'] = 3.14

ws3 = wb.create_sheet(title="Data")
for row in range(10, 20):
for col in range(27, 54):
ws3.cell(column=col, row=row, value="{0}".format(get_column_letter(col)))
print(ws3['AA10'].value)

wb.save(filename = dest_filename)


output 



Read an existing workbook

from openpyxl import load_workbook
wb = load_workbook(filename = 'empty_book.xlsx')
sheet_ranges = wb['range names']
print(sheet_ranges['D18'].value)

output 
>>> 3

Using formulae

from openpyxl import Workbook
wb = Workbook()
ws = wb.active
# add a simple formula
ws["A1"] = "=SUM(5, 4)"
wb.save("formula.xlsx")

output 

Following Are The tutorial on openpyxl For more you can check out Official openpyxl documentation 

0 Comments:

Post a Comment