2017-04-24 148 views
0

我使用此代碼的CSV副本:創建Excel工作表

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)) 

它創建一個副本不夠好,但它不會在列的格式複製。例如,列的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 

回答

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:]) 
+0

謝謝@ Tiny.D - 我用你的建議編輯了這個問題 - 但是出現錯誤,請參閱編輯。 – wazzahenry

+0

@wazzahenry你必須解開所有的值,在你的代碼中,你只需解壓3個變量'year,month,day',請檢查我更新的答案。幾乎在那裏 - –

+0

- 這僅適用於排除標題,並開始實際數據的範圍。有沒有一種方法可以包含標題? – wazzahenry

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

+0

謝謝,但其他列也有一定的格式,如貨幣和小數。我正在尋找能夠按原樣複製格式的內容,但我現在可以嘗試使用此格式。 – wazzahenry