python xlrd将xlsx转换为csv

时间:2013-08-07 20:49:26

标签: python xlrd

我正在尝试使用xlrd库将excel文件转换为csv文件。

但我收到了这个错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u0142' in position 2: ordinal not in range(128)

可以因为excel文件太大了吗?因为具有少量行的excel文件,一切正常。但是当我试图转换一个有近2000行的excel文件时,我收到了这个错误。

[UPDATE]

这是代码:

filepath = './attachments'
wb = xlrd.open_workbook(os.path.join(filepath, 'result.xls'))
sheet = wb.sheet_by_index(0)
fp = open(os.path.join(filepath, 'result.csv'), 'wb')
wr = csv.writer(fp, quoting=csv.QUOTE_ALL)
for rownum in xrange(sheet.nrows):
  wr.writerow(sheet.row_values(rownum))
fp.close()

这是追溯:

Traceback (most recent call last):
  File "MethodTest.py", line 11, in <module>
    wr.writerow(sheet.row_values(rownum))
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0142' in position 2: ordinal not in range(128)

1 个答案:

答案 0 :(得分:10)

您正在阅读包含ASCII范围之外的数据的Excel表格。

将unicode值写入CSV文件时,会发生自动编码,但是对于失败的ASCII字符范围之外的值。明确编码:

for rownum in xrange(sheet.nrows):
      wr.writerow([unicode(val).encode('utf8') for val in sheet.row_values(rownum)])

或者,对于Python 3(使用str()range()):

for rownum in range(sheet.nrows):
      wr.writerow([str(val).encode('utf8') for val in sheet.row_values(rownum)])

您可能需要根据需要选择不同的编码。