2015-11-30 77 views
0

我可以在單個Excel表格中將xlsx轉換爲csv。
我怎樣才能在單個Excel文件中的多個工作表的情況下做同樣的事情?
我曾嘗試:
如何使用python將多個xlsx表格轉換爲csv

workBook = xlrd.open_workbook(filePath) 
sheet_names = workBook.sheet_names() 
lenth = len(sheet_names) 
for i in range(0,lenth): 
    sheet = workBook.sheet_by_name(sheet_names[i]) 
    yourcsvFile = open(csvPath, 'wb') 
    wr = csv.writer(yourcsvFile, quoting=csv.QUOTE_ALL) 
    for rownum in xrange(sheet.nrows): 
     wr.writerow(sheet.row_values(rownum)) 
yourcsvFile.close() 
+0

什麼是你所得到的輸出?你想要每張紙都保存到一個單獨的CSV文件? – Simon

回答

0

試試這個

import sys 
import xlrd 
import csv 
filePath = sys.argv[1] # user input file 
csvPath = sys.argv[2] 
workBook = xlrd.open_workbook(filePath) 
sheet_names = workBook.sheet_names() 
list_sheet = [] 
lenth = len(sheet_names) 
for i in range(0,lenth): 
    sheet = workBook.sheet_by_name(sheet_names[i]) 
    list_sheet.append(sheet) 
yourcsvFile = open(csvPath, 'wb') 
wr = csv.writer(yourcsvFile, quoting=csv.QUOTE_ALL) 
total_row = list_sheet[0].ncols 
for k in xrange(0,1): 
    for rownum in xrange(list_sheet[k].nrows): 
     wr.writerow(list_sheet[k].row_values(rownum)) 
if len(sheet_names) > 1: 
    for k in xrange(1,len(list_sheet)): 
     if list_sheet[k].ncols != total_row: 
     continue 
    for rownum in xrange(1,list_sheet[k].nrows): 
     wr.writerow(list_sheet[k].row_values(rownum)) 

yourcsvFile.close()