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

7 投票
4 回答
16118 浏览
提问于 2025-04-18 00:09

我正在使用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

有人知道可能出什么问题了吗?

4 个回答

2

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 的信息。

2

你的问题其实是因为你用的是Python2的方式来打开文件。Python3会考虑到地区设置,所以如果你只是想往这个文件里写文本(你确实是这样做的),就应该用正确的选项把它当作文本文件来打开:

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

这里的encoding参数是用来指定输出的编码格式(不一定非得是utf-8),而Python3的文档里明确提到,对于csv文件对象,你应该指定newline=''

4

我推荐使用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')
7

试试这个

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

撰写回答