创buildExcel工作表的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)) 

它创build了一个足够好的副本,但不会跨列的格式进行复制。 例如, 2017-04-21date列被复制为数字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 

你可以使用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:]) 

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

 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