Saturday, 5 December 2015

Python - Write value to excel sheet using 'openpyxl' library.

Prerequisite:
Python is already installed.
'openpyxl' library is already installed.

Refer below url for installing 'openpyxl' library.
http://automation-home.blogspot.com/2015/12/python-installing-openpyxl-library.html

Sample Program:
import os
from openpyxl import load_workbook

wb = load_workbook(os.path.abspath(os.path.join(os.path.dirname(__file__),'testdata/Sample.xlsx')))
sheet = wb.get_sheet_by_name('Sheet1')
sheet['c1'].value= 'BookName'
wb.save(os.path.abspath(os.path.join(os.path.dirname(__file__),'testdata/Sample.xlsx')))

Executing program.

Note:
Excel sheet should be closed before executing the script.

Write value to excel sheet based on row and column number

Sample Program:
import os
from openpyxl import load_workbook

wb = load_workbook(os.path.abspath(os.path.join(os.path.dirname(__file__),'testdata/Sample.xlsx')))
sheet = wb.get_sheet_by_name('Sheet1')

sheet.cell(row=1, column=3).value='Books'
wb.save(os.path.abspath(os.path.join(os.path.dirname(__file__),'testdata/Sample.xlsx')))

c = sheet.cell(row=1, column=3).value
print(c) 

After executing the python script.
Note:
Excel sheet should be closed before executing the script.

No comments:

Post a Comment