我使用此代碼的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
謝謝@ Tiny.D - 我用你的建議編輯了這個問題 - 但是出現錯誤,請參閱編輯。 – wazzahenry
@wazzahenry你必須解開所有的值,在你的代碼中,你只需解壓3個變量'year,month,day',請檢查我更新的答案。幾乎在那裏 - –
- 這僅適用於排除標題,並開始實際數據的範圍。有沒有一種方法可以包含標題? – wazzahenry