简体   繁体   中英

Python: printing date to Excel- TypeError: coercing to str, need bytes, bytearray or buffer like object, int found

I'm trying to type the date into the next empty cell in the column on Excel and I'm getting the error in the title. So far I have this:

from win32com.client import Dispatch
import datetime
import pythoncom

#open workbook
xl = Dispatch('Excel.Application')
wb = xl.Workbooks.Add(' path to workbook ')
ws = wb.Worksheets(1)

#initialize values
empty = False
row = 1
col = 1
now = datetime.datetime.now()
day = str(now.day,"/")
month = str(now.month,"/")
year = str(now.year)
val = ws.Cells(row,col).value

#input date into Excel
#loop until empty cell is found in column
while not empty:
    val = ws.Cells(row,col).value
    print("Searching for next empty cell...")
    if val == None:
        print("Found empty cell! Writing date...")
        ws.Cells(row,col).value = (day + month + year)
        empty = True
    row += 1

#macro to save workbook
xl.Run('Save')

#close and release processes
wb.Close(True)
xl.Quit()

pythoncom.CoUninitialize()

Anyone have any ideas?

Thanks

edit the reason I am trying not to use the date as an int, is because when it is taken into Excel it only brings through the day (ie today would only bring through 17) and not the rest of the date.

Try

ws.Cells(row,col).value = datetime.datetime.now().strftime("%d/%m/%Y")

strftime converts date to string in your prefered format, there is no need to do it manually.

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