[問題] xlsx to csv

看板Python作者 (我不是那個女生,別丟了)時間13年前 (2012/10/12 07:40), 編輯推噓0(009)
留言9則, 4人參與, 最新討論串1/1
大家好~ 我想用python 把 .xlsx檔轉成 .csv檔 可是我的 .xlsx檔,每一個都有兩頁(sheet) 我目前的程式碼只能自動轉第一頁 但我想轉的是第二頁啊.. 可以請教大家要怎麼改嗎? 謝謝^^ # You must have Python for Windows (I used 2.6) and pywin32 extensions # installed and Excel 2007 on a Windows PC # Put this script into the dir where all the .XLSX files are and then cd to that dir # Usage: c:\python26\python.exe xls2csv.py import glob import os import time import win32com.client xlsx_files = glob.glob('*.xlsx') if len(xlsx_files) == 0: raise RuntimeError('No XLSX files to convert.') xlApp = win32com.client.Dispatch('Excel.Application') for file in xlsx_files: xlWb = xlApp.Workbooks.Open(os.path.join(os.getcwd(), file)) xlWb.SaveAs(os.path.join(os.getcwd(), file.split('.xlsx')[0] + '.csv'), FileFormat=6) xlWb.Close(SaveChanges = True) xlWB.Quit() xlApp.Quit() time.sleep(2) # give Excel time to quit, otherwise files may be locked # Uncomment the two lines below if you want the script to remove # the orig .xlsx files when done #for file in xlsx_files: # os.unlink(file) -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 92.225.101.155

10/12 11:01, , 1F
讓 selected sheet 切換到第二頁??
10/12 11:01, 1F

10/12 18:13, , 2F
請問樓上要怎麼切換?是改成file.split('.xlsx')[1]嗎
10/12 18:13, 2F

10/12 18:14, , 3F
我試過了,還是不行啊QQ
10/12 18:14, 3F

10/12 20:45, , 4F
open 跟SaveAs中間加上 xlWb.sheets(2).select
10/12 20:45, 4F
太感謝Catbert了 ^^, 我一直試著讓這個script能順利的用,已經試了快兩星期了 因為是寫程式的新手(我是唸語言學的T T),所以真的很頭痛@@ 真的很感謝你呢:) 另外,雖然已經轉檔成功,但python還是給我error message,: Traceback (most recent call last): File "C:/Users/User/Dropbox/Thesis/Statistic/data/all/xlsx2csv2.py", line 16, in <module> xlWb = xlApp.Workbooks.Open(file) File "<COMObject <unknown>>", line 8, in Open com_error: (-2147352567, '\xb5o\xa5\xcd\xa8\xd2\xa5~\xaa\xac\xaap\xa1C', (0, u'Microsoft Office Excel', u"Excel \u7121\u6cd5\u958b\u555f\u6a94\u6848 '~$01.xlsx'\uff0c\u56e0\u70ba\u6a94\u6848\u683c\u5f0f\u6216\u526f\u6a94\u540d\u7121\u6548\u3002\u8acb\u78ba\u8a8d\u6a94\u6848\u6c92\u6709\u640d\u6bc0\uff0c\u4e14\u526f\u6a94\u540d\u7b26\u5408\u6a94\u6848\u7684\u683c\u5f0f\u3002", u'C:\\Program Files\\Microsoft Office\\Office12\\1028\\XLMAIN11.CHM', 0, -2146827284), None) 請問這是什麼意思呢?可是還是可以轉檔成功啊? 謝謝大家的熱心幫忙:) ※ 編輯: sleepingbaby 來自: 85.179.144.1 (10/13 00:10)

10/13 01:44, , 5F
'Microsoft Office Excel', u"Excel 無法開啟檔案
10/13 01:44, 5F

10/13 01:44, , 6F
'~$01.xlsx',因為檔案格式或副檔名
10/13 01:44, 6F

10/13 01:45, , 7F
無效。請確認檔案沒有損毀,且副檔名符合檔案的格式。",
10/13 01:45, 7F

10/13 01:46, , 8F
轉出來的內容是這樣敘述的....
10/13 01:46, 8F

10/13 07:40, , 9F
謝謝樓上的o大 :)大家人都好好哦!真的很感謝大家!
10/13 07:40, 9F
文章代碼(AID): #1GTra37O (Python)
文章代碼(AID): #1GTra37O (Python)