Friday, 22 September 2017

How to open workbook and write contents to sheets ?


USE MODULE openpyxl
Only supports xlsx format (Not xls format)

# Import load_workbook module from package openpyxl and Import random module to create random values to fill in sheet
from openpyxl import load_workbook
import random
# Open the workbook
filePath = "Hello.xlsx"
fileRef = load_workbook(filePath, read_only=False) 

# Get sheet names
sheetNames = fileRef.get_sheet_names()
print(sheetNames)


# Pick a sheet and fill random values in cells from row 50 to 100 and columns from A to F (1 to 6)
sheet = fileRef.get_sheet_by_name('January_2017')
for row in range(51,100):
    for col in range(1,6):
        sheet.cell(column=col, row=row, value="%d

                    % random.randint(1,10000))

# Save the file after writing
fileRef.save(filePath)

No comments:

Post a Comment

Note: only a member of this blog may post a comment.