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

2024-05-19 02:51:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: csvimportyoursh错误openxlswr
3条回答

试试这个

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=''

相关问题 更多 >

    热门问题