Spi*_*ill 6 python csv xlrd python-3.x
我正在使用带有 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()
Run Code Online (Sandbox Code Playgroud)
有了这个,我收到了这个错误: TypeError: 'str' does not support the buffer interface
我尝试更改编码并用以下内容替换循环中的行:
wr.writerow(bytes(sh.row_values(rownum),'UTF-8'))
Run Code Online (Sandbox Code Playgroud)
但我收到此错误: 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()
Run Code Online (Sandbox Code Playgroud)
我建议使用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')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13326 次 |
最近记录: |