S
S
shmostertoster2016-10-16 14:43:03
Python
shmostertoster, 2016-10-16 14:43:03

How to write a list of dates in Excel?

Tell me how to write a list of dates in an excel book after executing this code.
Those. for example, in book1 on sheet1 in column D from the first to 145 cells.
it is impossible to write such cycle for dates.
Can't convert to str. Write line by line through the for loop - too.
Thank you!

from datetime import datetime, date, time
from dateutil.relativedelta import relativedelta
import xlrd, xlwt

wb = xlrd.open_workbook('Workbook.xls', encoding_override ="cp1251") # открываю книгу
ws = wb.sheet_by_name('Лист1')  # выбираю лист по названию

datas = ws.cell_value(0, 0) # выбираю колонку с датами
datetime_value = datetime(*xlrd.xldate_as_tuple(datas, 0))
datr = datetime_value.date()

wb2 = xlwt.Workbook('Workbook.xls')  # вот этот момент не очень понимаю, но без него не работает
                      # наверное это из-за того что в первом случае работает xlrd, а во втором xlwt
ws2 = wb2.add_sheet("Pi", cell_overwrite_ok=True)


for row_index in range(ws.nrows): # здесь по условиям прибавляется возраст к дате рождения
        dateq = ws.row(row_index)[0].value
        datetime_value2 = datetime(*xlrd.xldate_as_tuple(dateq, 0))
        datr2 = datetime_value2.date()

        sex = ws.row(row_index)[1].value


        if ws.row(row_index)[1].value == 'male':
            if datr2 <= date(1956, 12, 31):
                datr2 += relativedelta(years=60)
        if ws.row(row_index)[1].value == "female":
            if datr2 <= date(1961, 12, 31):
                datr2 += relativedelta(years=55)
            print(datr2.strftime('%d.%m.%Y'))

        i = 1

        style1 = xlwt.easyxf(num_format_str='DD.MM.YYYY')
        ws2.write(i, 2, datr2, style1)
        i =+ i

print("The End")

wb2.save('write_only_file.xls')

The code displays the full list of changed dates to the console, but only the last value is written to the file.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuri, 2016-10-16
@shmostertoster

# вариант 1
ws2.write(2, datr2.isoformat(), style1)
# вариант 2 - https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
ws2.write(2, datr2.strftime('%d-%m-%Y'), style1)

I
Igor Nikolaev, 2016-10-16
@nightvich

from datetime import datetime, date
from dateutil.relativedelta import relativedelta
from xlrd import *
from xlrd.xldate import xldate_from_date_tuple, xldate_from_datetime_tuple
from xlwt import *
import xlrd, xlwt
daded366927040aa84031d48c5b49304.jpeg

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question