创建Excel工作表的CSV副本

时间:2017-04-24 07:38:08

标签: python excel vba csv

我正在使用此代码:

import xlrd
import csv

with xlrd.open_workbook('iSolar Transactions (CURRENT).xlsm') as wb:
    sh = wb.sheet_by_index(2)  # or wb.sheet_by_name('name_of_the_sheet_here')
    with open('client_history.csv', 'wb') as f:
        c = csv.writer(f)
        for r in range(sh.nrows):
            c.writerow(sh.row_values(r))

它创建的副本足够好,但它不会复制列的格式。例如,date列的2017-04-21列将作为数字41562复制。有没有办法复制格式呢?

编辑: 使用Tiny.D的代码:

import xlrd
import csv
from datetime import datetime

with xlrd.open_workbook('iSolar Transactions (CURRENT).xlsm') as wb:
    sh = wb.sheet_by_index(2)  # or wb.sheet_by_name('name_of_the_sheet_here')
    column_date = 4 #suppose the first column in your work book is date    
    with open('client_history.csv', 'wb') as f:
        c = csv.writer(f)
        for r in range(1,sh.nrows):
            year, month, day= xlrd.xldate_as_tuple(int(sh.row_values(r)[column_date]), wb.datemode) 
            py_date = datetime(year, month, day)
            c.writerow([py_date]+sh.row_values(r)[1:])

我收到此错误:

Traceback (most recent call last):
  File "C:/Users/warren.si/Dropbox/iShack/Records/#04 Field Operations/#01 client recruitment & management/Client Database/#09 Client Accounts/client_history_tocsv3.py", line 11, in <module>
    year, month, day= xlrd.xldate_as_tuple(int(sh.row_values(r)[column_date]), wb.datemode)
ValueError: too many values to unpack

2 个答案:

答案 0 :(得分:1)

您可以使用 xldate_as_datetime 转换为Python的日期时间格式:

In [4]: xlrd.xldate.xldate_as_datetime(41562, 1)
Out[4]: datetime.datetime(2017, 10, 16, 0, 0)

参考文献:

http://xlrd.readthedocs.io/en/latest/api.html#xlrd.xldate.xldate_as_datetime http://xlrd.readthedocs.io/en/latest/dates.html

答案 1 :(得分:1)

您可以使用xldate_as_tuple,以下是基于您的代码修改后的版本:

import xlrd
import csv
from datetime import datetime

with xlrd.open_workbook('iSolar Transactions (CURRENT).xlsx') as wb:
    sh = wb.sheet_by_index(2)  # or wb.sheet_by_name('name_of_the_sheet_here')
    column_date = 4 #suppose the 5th column in your work book is date    
    with open('client_history.csv', 'wb') as f:
        c = csv.writer(f)
        c.writerow(sh.row_values(0)) # write header to csv
        for r in range(1,sh.nrows):
            year, month, day, hour, minute, sec = xlrd.xldate_as_tuple(int(sh.row_values(r)[column_date]), wb.datemode) #unpack all values here, not just year, month, day
            py_date = datetime(year, month, day, hour, minute)
            c.writerow(sh.row_values(r)[:3]+[py_date] + sh.row_values(r)[5:])