Creating a new Excel file

In this section, we will learn to create a new Excel file using openpyxl. Create a script called create_excel.py and write the following content in it:

from openpyxl import Workbook

book_obj = Workbook()
excel_sheet = book_obj.active
excel_sheet['A1'] = 'Name'
excel_sheet['A2'] = 'student'
excel_sheet['B1'] = 'age'
excel_sheet['B2'] = '24'

book_obj.save("test.xlsx")
print("Excel created successfully")

Run the script and you will get the following output:

student@ubuntu:~/work$ python3 create_excel.py

Following is the output:

Excel created successfully

Now, check your current working directory and you will find that test.xlsx has been created successfully. In the preceding example, we write data into four cells. Then, from the openpyxl module, we import the Workbook class. A workbook is the container for all other parts of the document. Next, we set the reference object to the active sheet and write values in the cells A1, A2 and B1, B2. Finally, we've written the contents to the test.xlsx file with the save() method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset