简体   繁体   中英

openpyxl - format column for date only

Using openpyxl version 2.6.1

There's a number of unsolved threads on here about trying to format columns. I understand you cannot format an entire column at the moment...only individual cells? Still, I seem unable to do even that. I'm trying to format a column as 'mm/dd/yyyy' . I also know NumberFormat() has been removed. What I have tried last, and "works" (meaning it's the first time I got code to run and post out into the excel spreadsheet) was the code below...but it does not format the column, the result I get in cell B2 is TRUE . What am I missing here?

from openpyxl.styles import is_date_format, numbers

s = numbers.is_date_format('mm/dd/yy')
daily_runs_ws['B2'] = s

The current cell format (without trying to edit it) is 11/14/2019 12:00:00 AM for example.

This works for me. Openpyxl allows datetime. So, I suggest something like this:

import datetime
import openpyxl

dttm = datetime.datetime.strptime("09/12/2018", "%m/%d/%Y")
print(dttm)
cell = ws['A1']
cell.value = dttm
cell.number_format = 'YYYY MMM DD'

The way to format a cell is using .number_format = "format" .

You are right, at the moment you can't format an entire column as a date using only openpyxl, but you can format any cells (including all written cells in a column) on a document the following way:

import openpyxl

document = openpyxl.load_workbook("document.xlsx")  # Opens excel document
sheet = document.active  # Sets active sheet

# To format all written cells in a column (Ex. column "B")
for cell in sheet["B"]:
    cell.number_format = "DD/MM/YYYY"

Note that it is very relevant that this only formats the written cells in a column , all other blank cells after the last written cell (does not apply for blank cells in between written cells) remains with a "General" format unless previously formatted.

numbers.is_date_format is a function that openpyxl uses to determine whether a number format is for dates and times. The way you use it will return True and set the value of B2 to True. Which is probably not what you want.

I suggest you read the section of the openpyxl documentation that covers styles. That should answer your questions.

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