For the next two pieces of code, I'll assume the existence of the following:
header = ["Device Name", "Uptime", "CPU", "Count of users logged in"]
data = [
('ns1', '200 days', '10%', '15'),
('ns2', '23 days', '12%', '23'),
('ns3', '45 days', '56%', '108')
]
Using CSV makes it for a bit easier code and it's easy to deploy on any machine, because it doesn't require to install any further package (csv
comes standard with Python):
import csv
with open('output.csv', 'wb') as csvfile:
spamwriter = csv.writer(csvfile, dialect='excel')
spamwriter.writerow(header)
for row in data:
spamwriter.writerow(row)
would produce the following output.csv
file:
Device Name,Uptime,CPU,Count of users logged in
ns1,200 days,10%,15
ns2,23 days,12%,23
ns3,45 days,56%,108
Now, if you really want to use xlwt
, here would be the equivalent (adding extra yellow background color for the header):
import xlwt
book = xlwt.Workbook()
sheet = book.add_sheet("foobar")
# Put the header in the appropriate cells...
style = xlwt.easyxf('pattern: pattern solid, fore-colour yellow')
for col, text in enumerate(header):
sheet.write(0, col, text, style)
# Now, let's write the contents
for row, data_in_row in enumerate(data):
for col, text in enumerate(data_in_row):
sheet.write(row + 1, col, text)
book.save("example.xls")