xls 到 csv 转换器 [英] xls to csv converter

查看:44
本文介绍了xls 到 csv 转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python 中使用 win32.client 将我的 .xlsx 和 .xls 文件转换为 .csv.当我执行此代码时,它给出了错误.我的代码是:

I am using win32.client in python for converting my .xlsx and .xls file into a .csv. When I execute this code it's giving an error. My code is:

def convertXLS2CSV(aFile):
    '''converts a MS Excel file to csv w/ the same name in the same directory'''

    print "------ beginning to convert XLS to CSV ------"

    try:
        import win32com.client, os
        from win32com.client import constants as c
        excel = win32com.client.Dispatch('Excel.Application')

        fileDir, fileName = os.path.split(aFile)
        nameOnly = os.path.splitext(fileName)
        newName = nameOnly[0] + ".csv"
        outCSV = os.path.join(fileDir, newName)
        workbook = excel.Workbooks.Open(aFile)
        workbook.SaveAs(outCSV, c.xlCSVMSDOS) # 24 represents xlCSVMSDOS
        workbook.Close(False)
        excel.Quit()
        del excel

        print "...Converted " + nameOnly + " to CSV"
    except:
        print ">>>>>>> FAILED to convert " + aFile + " to CSV!"

convertXLS2CSV("G:\hello.xlsx")

我无法在此代码中找到错误.请帮忙.

I am not able to find the error in this code. Please help.

推荐答案

我会使用 xlrd - 它更快、跨平台并且直接处理文件.需要注意的一件事 - 它不适用于 xlsx 文件 - 因此您必须将 Excel 文件另存为 xls. 从 0.8.0 版开始,xlrd 读取 XLS 和 XLSX 文件.

I would use xlrd - it's faster, cross platform and works directly with the file. One thing to note - it doesn't work on xlsx files - so you'd have to save your Excel file as xls. As of version 0.8.0, xlrd reads both XLS and XLSX files.

import xlrd
import csv

def csv_from_excel():
    wb = xlrd.open_workbook('your_workbook.xls')
    sh = wb.sheet_by_name('Sheet1')
    your_csv_file = open('your_csv_file.csv', 'wb')
    wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)

    for rownum in xrange(sh.nrows):
        wr.writerow(sh.row_values(rownum))

    your_csv_file.close()

这篇关于xls 到 csv 转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆