作者sleepingbaby (我不是那个女生,别丢了)
看板Python
标题[问题] xlsx to csv
时间Fri Oct 12 07:40:49 2012
大家好~
我想用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
1F:→ KSJ:让 selected sheet 切换到第二页?? 10/12 11:01
2F:→ sleepingbaby:请问楼上要怎麽切换?是改成file.split('.xlsx')[1]吗 10/12 18:13
3F:→ sleepingbaby:我试过了,还是不行啊QQ 10/12 18:14
4F:→ Catbert:open 跟SaveAs中间加上 xlWb.sheets(2).select 10/12 20:45
太感谢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)
5F:→ odami:'Microsoft Office Excel', u"Excel 无法开启档案 10/13 01:44
6F:→ odami:'~$01.xlsx',因为档案格式或副档名 10/13 01:44
7F:→ odami:无效。请确认档案没有损毁,且副档名符合档案的格式。", 10/13 01:45
8F:→ odami:转出来的内容是这样叙述的.... 10/13 01:46
9F:→ sleepingbaby:谢谢楼上的o大 :)大家人都好好哦!真的很感谢大家! 10/13 07:40