【问题标题】:Converting xls to csv in Python 3 using xlrd使用 xlrd 在 Python 3 中将 xls 转换为 csv
【发布时间】:2014-05-06 11:27:21
【问题描述】:

我正在使用带有 xlrd 和 csv 模块的 Python 3.3 将 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

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

【问题讨论】:

    标签: python csv python-3.x xlrd


    【解决方案1】:

    试试这个

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

    【讨论】:

      【解决方案2】:

      我建议使用 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')
      

      【讨论】:

        【解决方案3】:

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

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

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

        【讨论】:

          【解决方案4】:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-06-14
            • 1970-01-01
            • 2015-05-29
            • 2015-11-11
            • 1970-01-01
            相关资源
            最近更新 更多