Basic usage - xlwt

Learn how to save data as an Excel file using xlwt.


Example 1

import xlwt

wbwt = xlwt.Workbook(encoding='utf-8')
ws = wbwt.add_sheet('Sheet1', cell_overwrite_ok=True)
wbwt.save('xlwt_save01.xls')

Create a workbook using xlwt.Workbook() .

Then add one sheet using the add_sheet() method. The first parameter is the name of the sheet, and if cell_overwrite_ok is True, overwriting is allowed.

Use save() to save your workbook under the name ‘xlwt_save01.xls’. One Excel file will be created in that path.

There is no data in the Excel file yet as shown below.


_images/xlwt_basic01.png


Example 2

import xlwt

wbwt = xlwt.Workbook(encoding='utf-8')
ws = wbwt.add_sheet('Sheet1', cell_overwrite_ok=True)

ws.write(0, 0, 100)
ws.write(1, 1, 200)
ws.write(2, 2, 300)

wbwt.save('xlwt_save02.xls')

Create one sheet using add_sheet() . ws refers to the first sheet.

Use write() to write values on the sheet. The first and second parameters of write() are the positions of rows and columns, and the third enter the value you want to write.

save() is used to save to an Excel file named ‘xlwt_save02.xls’.

You can see that 100, 200, 300 are stored in the positions of (0, 0), (1, 1), (2, 2), respectively.


_images/xlwt_basic02.png


Example 3

import xlwt

wbwt = xlwt.Workbook(encoding='utf-8')
ws = wbwt.add_sheet('Sheet1', cell_overwrite_ok=True)

for i in range(10):
    for j in range(10):
        ws.write(i, j, (i+j)**2)

wbwt.save('xlwt_save03.xls')

In the same way, create one workbook and add one sheet.

We used the for loop to place a value equal to the square of (i+j) in the position of (i, j).

The results are as follows.


_images/xlwt_basic03.png

Prev/Next