简体   繁体   中英

How to write python output to an excel sheet?

I have used below code to import data from Book9.xlsx (Sheet name is Sheet 1).Also formatted the Date column values to the desired format.Now I want to write back the python out put to a different sheet of same work book.I have found examples to write values to new sheet.But all those values are hard coded ones,not from python output.I am a beginner only.Your help is greatly appreciated.Thank You.

import openpyxl
import datetime
wb = openpyxl.load_workbook('Book9.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')

print ("Date\tUser\tApp")

for r in range(2,6): 
    d=sheet.cell(row=r,column=1) 
    e=sheet.cell(row=r,column=2)
    f=sheet.cell(row=r,column=3)
    x = datetime.datetime.strptime(d.value,"%b %d, %Y, %I:%M:%S %p")
    y = x.strftime("%d/%m/%Y %H:%M")
    print((y)+'\t'+(e.value)+'\t'+(f.value))

The OpenPyXL supports writing to the excel file as well.

You may add a new sheet using following code:

wb.create_sheet(title="Output")

Write all your data and finally save your file using following code:

wb.save(absolute_file_path_and_name)

For further details read OpenPyXl documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM