DEV Community

petercour
petercour

Posted on

2 2

Write excel from code

You can write Excel files with Python. Excel is a very popular file format outside of the development community. Finance and many other fields heavily use Excel.

The module xlsxwriter lets you do that, first install that module.
Then load the module in Python.

#!/usr/bin/python3
#coding: utf-8
import xlsxwriter
Enter fullscreen mode Exit fullscreen mode

Create a file and a sheet to work in

file_name = "data.xlsx"
workbook = xlsxwriter.Workbook(file_name)
worksheet = workbook.add_worksheet('sheet1')
Enter fullscreen mode Exit fullscreen mode

Write the header to the excel sheet

worksheet.write(0, 0, 'id')
worksheet.write(0,1, 'name')
worksheet.write(0,2, 'class')
worksheet.write(0,3, 'data')
Enter fullscreen mode Exit fullscreen mode

And finally write the data

worksheet.write_row(1, 0, [1, 2, 3])
worksheet.write_column('D2', ['a', 'b', 'c'])

workbook.close()
Enter fullscreen mode Exit fullscreen mode

Put it all together to write the excel file. It gives you this code:

#!/usr/bin/python3
#coding: utf-8
import xlsxwriter

file_name = "data.xlsx"
workbook = xlsxwriter.Workbook(file_name)
worksheet = workbook.add_worksheet('sheet1')

worksheet.write(0, 0, 'id')
worksheet.write(0,1, 'name')
worksheet.write(0,2, 'class')
worksheet.write(0,3, 'data')

worksheet.write_row(1, 0, [1, 2, 3])
worksheet.write_column('D2', ['a', 'b', 'c'])

workbook.close()
Enter fullscreen mode Exit fullscreen mode

Related links:

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay