简体   繁体   中英

pyExcelerator date format

I have been using pyExcelerator library for a while, it works nicely. Now, I would like to be able to export python dates as Date format in the excel sheet. I cannot find out (I read the documentation) how to do. Any suggestions ?

Option 1 :

Just convert string to datetime type you've got from parsing. Here I assume that you have fixed date format:

import csv
from datetime import datetime
date_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

rows = ['foo', 'bar', date_object]

with open('export.csv', 'wb') as csv_file:
    writer = csv.writer(csv_file, delimiter=',', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(rows)

Option 2

Use xlwt module. Example:

#!/usr/bin/env python
# -*- coding: windows-1251 -*-
# Copyright (C) 2005 Kiseliov Roman

from xlwt import *
from datetime import datetime

w = Workbook()
ws = w.add_sheet('Hey, Dude')

fmts = [
    'M/D/YY',
    'D-MMM-YY',
    'D-MMM',
    'MMM-YY',
    'h:mm AM/PM',
    'h:mm:ss AM/PM',
    'h:mm',
    'h:mm:ss',
    'M/D/YY h:mm',
    'mm:ss',
    '[h]:mm:ss',
    'mm:ss.0',
]

i = 0
for fmt in fmts:
    ws.write(i, 0, fmt)

    style = XFStyle()
    style.num_format_str = fmt

    ws.write(i, 4, datetime.now(), style)

    i += 1

w.save('dates.xls')

More examples: https://github.com/python-excel/xlwt/tree/master/xlwt/examples

This is a function I made. Thought someone out there might find some use for it.

import datetime
from pyexcelerate import Workbook
from pyexcelerate.Format import Format

def data_to_xlsx(data):
    wb = Workbook()
    for sheet_name in data:
        headers = data[sheet_name]['headers']
        rows = [row.itervalues() if isinstance(row, dict) else row for row in data[sheet_name]['objects']]
        ws = wb.new_sheet(sheet_name, data=[headers]+rows)
        ws.range((1, 1), (1, len(headers))).style.font.bold = True
        datecols = []
        if rows:
            for x in xrange(len(rows[0])):
                for row in rows:
                    value = row[x]
                    if value is not None:
                        if isinstance(value, datetime.datetime):
                            datecols.append((x, 'yyyy-mm-dd hh:mm:ss'))
                        elif isinstance(value, datetime.date):
                            datecols.append((x, 'yyyy-mm-dd'))
                        elif isinstance(value, datetime.time):
                            datecols.append((x, 'hh:mm:ss'))
                        break
            for col, format in datecols:
                ws.range((2, col+1), (len(rows)+1, col+1)).style.format = Format(format)
    return wb

It takes a nested dict which includes the necessary things such as sheet names, headers, rows and returns a Workbook object. The function basically inserts the data into a worksheet and then applies either datetime, date or time formats to entire columns.

An example of a parameter would be:

data = {
    'List': {
        'headers': ('First name', 'Last name'),
        'objects': [
            ('Duane', 'Chow'),
            ('Chris', 'Mara'),
            ('Dan' , 'Wachsberger'),
            ('Ron' , 'Forenall'),
            ('Jack' , 'McGann'),
            ('Andrew' , 'Holt'),
            ('Anthony' , 'Perez'),
            ('Isaac' , 'Conley'),
            ('William' , 'Moniz'),
            ('Harris' , 'Boivin'),
            ('Raymond' , 'Martinez')
        ]
    }
}
wb = data_to_xlsx(data)

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