Writing Excel files using Python is quite easy, using the xlwt package. Similar to xlrd mentioned in an earlier post, xlwt allows one to write Excel files from scratch using Python.
A brief reminded of Excel files (as mentioned in an earlier post) follows, to help people understand how Excel files work.The program stores data in what is called aWorkbook. Think of this as the file on your computer (the .xls). A Workbook can then have one or more Sheets, the little tabs on the bottom left corner usually. Within each Sheet, you can find an arrangement of Cells in a matrix form, which are referenced by Column Name and Row Number (so the top left cell is A1, the one directly to its right is A2, the one below is B2, etc. The image should help shed some light if you are not familiar with the concept of spreadsheets.To create your own Excel files using Python, all you need to have is the xlwt package. The workflow for such a process is simple: create a workbook, create a sheet within the workbook, start writing data into the cells of the sheet. Sample code shown below should help you get started quickly and easily.
|
1
2
3
4
5
6
7
8
9
10
11
12
|
import xlwt # Import the packagewbook = xlwt.Workbook() # Create a new workbooksheet = wbook.add_sheet("Sample Sheet") # Create a sheetdata = "Sample data" # Something to write into the sheetfor rowx in range(5):# Loop through the first five rowsfor colx in range(5):# Loop through the first five columns# Write the data to rox, columnsheet.write(rowx, colx, data)# Save our workbook on the harddrivewbook.save("myFile.xls") |
And that is all you need. You just created a brand new Excel file called myFile.xls within Python without the use of Excel itself. The file has the first 5 rows and columns filled out with the text “Sample data”. It is trivial then to change this so it can save any data you want with a little bit more of Python.