xls到csv转换器

问题描述 投票:46回答:11

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

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")

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

python excel csv xls export-to-csv
11个回答
62
投票

我会使用xlrd - 它更快,跨平台并直接与文件一起工作。 有一点需要注意 - 它不适用于xlsx文件 - 所以你必须将你的Excel文件保存为xls。 编辑:从版本0.8.0开始,xlrd读取XLS和XLSX文件。

 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()

0
投票

我们可以使用Python的Pandas lib将xls文件转换为csv文件。下面的代码将xls文件转换为csv文件。将pandas导入为pd

从本地路径读取Excel文件:

df = pd.read_excel("C:/Users/IBM_ADMIN/BU GPA Scorecard.xlsx",sheetname=1)

列上的修剪空间:

df.columns = df.columns.str.strip()

将数据帧发送到CSV文件,该文件将是管道符号分隔且没有索引:

df.to_csv("C:/Users/IBM_ADMIN/BU GPA Scorecard csv.csv",sep="|",index=False)

0
投票

尽管我不喜欢依赖于Windows平台的专有软件,但我测试的csvkit for .xls(使用xlrd)无法正确解析日期(即使使用命令行参数来指定strptime)格式)。

例如,this xls file,当用csvkit解析时,会将G112/31/2002转换为37621,而当通过excel转换为csv时 - > save_as(使用下面),单元格G1将是"December 31, 2002"

import re
import os
from win32com.client import Dispatch
xlCSVMSDOS = 24

class CsvConverter(object):
    def __init__(self, *, input_dir, output_dir):
        self._excel = None
        self.input_dir = input_dir
        self.output_dir = output_dir

        if not os.path.isdir(self.output_dir):
            os.makedirs(self.output_dir)

    def isSheetEmpty(self, sheet):
        # https://archive.is/RuxR7
        # WorksheetFunction.CountA(ActiveSheet.UsedRange) = 0 And ActiveSheet.Shapes.Count = 0

        return \
            (not self._excel.WorksheetFunction.CountA(sheet.UsedRange)) \
            and \
            (not sheet.Shapes.Count)

    def getNonEmptySheets(self, wb, as_name=False):
        return [ \
            (sheet.Name if as_name else sheet) \
            for sheet in wb.Sheets \
            if not self.isSheetEmpty(sheet) \
        ]

    def saveWorkbookAsCsv(self, wb, csv_path):
        non_empty_sheet_names = self.getNonEmptySheets(wb, as_name=True)

        assert (len(non_empty_sheet_names) == 1), \
            "Expected exactly 1 sheet but found %i non-empty sheets: '%s'" \
            %(
                len(non_empty_sheet_names),
                "', '".join(name.replace("'", r"\'") for name in non_empty_sheet_names)
            )

        wb.Worksheets(non_empty_sheet_names[0]).SaveAs(csv_path, xlCSVMSDOS)
        wb.Saved = 1

    def isXlsFilename(self, filename):
        return bool(re.search(r'(?i)\.xls$', filename))

    def batchConvertXlsToCsv(self):
        xls_names = tuple( filename for filename in next(os.walk(self.input_dir))[2] if self.isXlsFilename(filename) )

        self._excel = Dispatch('Excel.Application')
        try:
            for xls_name in xls_names:
                csv_path = os.path.join(self.output_dir, '%s.csv' %os.path.splitext(xls_name)[0])
                if not os.path.isfile(csv_path):
                    workbook = self._excel.Workbooks.Open(os.path.join(self.input_dir, xls_name))
                    try:
                        self.saveWorkbookAsCsv(workbook, csv_path)
                    finally:
                        workbook.Close()
        finally:
            if not len(self._excel.Workbooks):
                self._excel.Quit()

            self._excel = None

if __name__ == '__main__':
    self = CsvConverter(
        input_dir='C:\\data\\xls\\',
        output_dir='C:\\data\\csv\\'
    )

    self.batchConvertXlsToCsv()

上面将采用包含.xls的input_dir并将它们输出到output_dir作为.csv - 它将assert在.xls中正好有1个非空表;如果您需要将多个工作表处理成多个csv,那么您需要编辑saveWorkbookAsCsv


42
投票

我会用pandas。计算量很大的部分是用cython或c-extension编写的,以加快进程并且语法非常干净。例如,如果要将“Sheet1”从文件“your_workbook.xls”转换为文件“your_csv.csv”,则只需使用顶级函数read_excelto_csv类中的方法DataFrame,如下所示:

import pandas as pd
data_xls = pd.read_excel('your_workbook.xls', 'Sheet1', index_col=None)
data_xls.to_csv('your_csv.csv', encoding='utf-8')

设置encoding='utf-8'减轻了其他答案中提到的UnicodeEncodeError


32
投票

也许有人发现这个随时可用的代码片段很有用。它允许从Excel工作簿中的所有电子表格创建CSV。

# -*- coding: utf-8 -*-
import xlrd
import csv
from os import sys

def csv_from_excel(excel_file):
    workbook = xlrd.open_workbook(excel_file)
    all_worksheets = workbook.sheet_names()
    for worksheet_name in all_worksheets:
        worksheet = workbook.sheet_by_name(worksheet_name)
        with open('{}.csv'.format(worksheet_name), 'wb') as your_csv_file:
            wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)
            for rownum in xrange(worksheet.nrows):
                wr.writerow([unicode(entry).encode("utf-8") for entry in worksheet.row_values(rownum)])

if __name__ == "__main__":
    csv_from_excel(sys.argv[1])

21
投票

我使用csvkit,它使用xlrd(用于xls)和openpyxl(用于xlsx)将几乎任何表格数据转换为csv。

安装后,依赖于它,这是一个问题:

python in2csv myfile > myoutput.csv

它会处理所有格式检测问题,因此您可以将其传递给任何表格数据源。它也是跨平台的(没有win32依赖)。


3
投票

@andi我测试了你的代码,它很棒,但是

在我的床单上有一个这样的栏目

2013-03-06T04:00:00

同一单元格中的日期和时间

它在导出过程中出现乱码,在导出的文件中就是这样

41275.0416667

其他栏目还可以。

另一方面,csvkit对该列没有问题,但只导出一张表,而我的文件有很多。


3
投票

xlsx2csv比熊猫和xlrd快。

xlsx2csv -s 0 crunchbase_monthly_.xlsx cruchbase

excel文件通常带有n sheetname。

-s is sheetname index.

然后,将创建cruchbase文件夹,每张属于xlsx的工作表将转换为单个csv。

附: csvkit也很棒。


1
投票

引用answer中的Scott Ming,它与包含多个工作表的工作簿一起使用:

这是一个python脚本getsheets.pymirror),你应该在使用之前安装pandasxlrd

运行这个:

pip3 install pandas xlrd  # or `pip install pandas xlrd`

它是如何工作的?

$ python3 getsheets.py -h
Usage: getsheets.py [OPTIONS] INPUTFILE

Convert a Excel file with multiple sheets to several file with one sheet.

Examples:

    getsheets filename

    getsheets filename -f csv

Options:
-f, --format [xlsx|csv]  Default xlsx.
-h, --help               Show this message and exit.

转换为几个xlsx:

$ python3 getsheets.py goods_temp.xlsx
Sheet.xlsx Done!
Sheet1.xlsx Done!

All Done!

转换为几个csv:

$ python3 getsheets.py goods_temp.xlsx -f csv
Sheet.csv Done!
Sheet1.csv Done!

All Done!

getsheets.py

# -*- coding: utf-8 -*-

import click
import os
import pandas as pd


def file_split(file):
    s = file.split('.')
    name = '.'.join(s[:-1])  # get directory name
    return name


def getsheets(inputfile, fileformat):
    name = file_split(inputfile)
    try:
        os.makedirs(name)
    except:
        pass

    df1 = pd.ExcelFile(inputfile)
    for x in df1.sheet_names:
        print(x + '.' + fileformat, 'Done!')
        df2 = pd.read_excel(inputfile, sheetname=x)
        filename = os.path.join(name, x + '.' + fileformat)
        if fileformat == 'csv':
            df2.to_csv(filename, index=False)
        else:
            df2.to_excel(filename, index=False)
    print('\nAll Done!')


CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])


@click.command(context_settings=CONTEXT_SETTINGS)
@click.argument('inputfile')
@click.option('-f', '--format', type=click.Choice([
    'xlsx', 'csv']), default='xlsx', help='Default xlsx.')
def cli(inputfile, format):
    '''Convert a Excel file with multiple sheets to several file with one sheet.

    Examples:

    \b
        getsheets filename

    \b
        getsheets filename -f csv
    '''
    if format == 'csv':
        getsheets(inputfile, 'csv')
    else:
        getsheets(inputfile, 'xlsx')


cli()

0
投票

使用xlrd是一种有缺陷的方法,因为您在Excel中丢失了日期格式。

我的用例如下。

获取包含多个工作表的Excel文件,并将每个工作表转换为自己的文件。

我使用xlsx2csv库并使用子进程调用它。

import csv
import sys, os, json, re, time
import subprocess

def csv_from_excel(fname):
    subprocess.Popen(["xlsx2csv " + fname + " --all -d '|' -i -p "
                      "'<New Sheet>' > " + 'test.csv'], shell=True)

    return

lstSheets = csv_from_excel(sys.argv[1])

time.sleep(3) # system needs to wait a second to recognize the file was  written

with open('[YOUR PATH]/test.csv') as f:
    lines = f.readlines()
    firstSheet = True

    for line in lines:
        if line.startswith('<New Sheet>'):
            if firstSheet:
                sh_2_fname = line.replace('<New Sheet>', '').strip().replace(' - ', '_').replace(' ','_')
                print(sh_2_fname)
                sh2f = open(sh_2_fname+".csv", "w")
                firstSheet = False
            else:
                sh2f.close()
                sh_2_fname = line.replace('<New Sheet>', '').strip().replace(' - ', '_').replace(' ','_')
                print(sh_2_fname)
                sh2f = open(sh_2_fname+".csv", "w")
        else:
            sh2f.write(line)
sh2f.close()

0
投票

我已经测试了所有的水壶,但它们对我来说都太慢了。如果安装了Excel,则可以使用COM。

我认为最初它会慢,因为它将加载实际的Excel应用程序的一切,但它不适用于大文件。也许是因为打开和保存文件的算法运行了一个经过大量优化的编译代码,微软的人毕竟为它赚了不少钱。

import sys
import os
import glob
from win32com.client import Dispatch

def main(path):
    excel = Dispatch("Excel.Application")
    if is_full_path(path):
        process_file(excel, path)
    else:
        files = glob.glob(path)
        for file_path in files:
            process_file(excel, file_path)
    excel.Quit()

def process_file(excel, path):
    fullpath = os.path.abspath(path)
    full_csv_path = os.path.splitext(fullpath)[0] + '.csv'
    workbook = excel.Workbooks.Open(fullpath)
    workbook.Worksheets(1).SaveAs(full_csv_path, 6)
    workbook.Saved = 1
    workbook.Close()


def is_full_path(path):
    return path.find(":") > -1

if __name__ == '__main__':
    main(sys.argv[1])

这是非常原始的代码,不会检查错误,打印帮助或任何东西,它只会为每个文件创建一个csv文件,该文件与您在函数中输入的模式相匹配,因此您可以批量处理大量文件,只启动excel应用程序一旦。

© www.soinside.com 2019 - 2024. All rights reserved.