繁体   English   中英

使用xlrd在Python 3中将xls转换为csv

[英]Converting xls to csv in Python 3 using xlrd

我正在使用Python 3.3与xlrd和csv模块将xls文件转换为csv。 这是我的代码:

import xlrd
import csv

def csv_from_excel():

    wb = xlrd.open_workbook('MySpreadsheet.xls')
    sh = wb.sheet_by_name('Sheet1')
    your_csv_file = open('test_output.csv', 'wb')
    wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)

    for rownum in range(sh.nrows):

        wr.writerow(sh.row_values(rownum))

    your_csv_file.close()

因此我收到此错误: TypeError: 'str' does not support the buffer interface

我尝试更改编码并用以下内容替换循环内的行:

wr.writerow(bytes(sh.row_values(rownum),'UTF-8'))

但我收到此错误: TypeError: encoding or errors without a string argument

有谁知道可能会出错?

尝试这个

import xlrd
import csv

def csv_from_excel():
    wb = xlrd.open_workbook('MySpreadsheet.xlsx')
    sh = wb.sheet_by_name('Sheet1')
    your_csv_file = open('output.csv', 'w', encoding='utf8')
    wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)

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

    your_csv_file.close()

我建议使用pandas库来完成这项任务

import pandas as pd
xls = pd.ExcelFile('file.xlsx')
df = xls.parse(sheetname="Sheet1", index_col=None, na_values=['NA'])
df.to_csv('file.csv')

您的问题基本上是用Python2语义打开文件。 Python3是区域设置感知的,所以如果您只想将文本写入此文件(并且确实如此),请将其打开为具有正确选项的文本文件:

your_csv_file = open('test_output.csv', 'w', encoding='utf-8', newline='')

encoding参数指定输出编码(它不必是utf-8),csv的Python3文档明确指出你应该为csv文件对象指定newline=''

使用pandas更快捷的方法:

import pandas as pd

xls_file = pd.read_excel('MySpreadsheet.xls', sheetname="Sheet1")
xls_file.to_csv('MySpreadsheet.csv', index = False)
#remove the index because pandas automatically indexes the first column of CSV files.

您可以在此处阅读有关pandas.read_excel的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM