【问题标题】:Convert xlsm to csv将 xlsm 转换为 csv
【发布时间】:2016-12-19 20:45:41
【问题描述】:

我正在解析 vba 宏加密的 Excel 文件并尝试复制 Excel 文件中的所有工作表,但我的脚本一直在爆炸。我在我的 sn-p 中做错了什么。

import csv
import xlrd

workbook = xlrd.open_workbook('P:/NEW.xlsm')
for sheet in workbook.sheets():
    with open('{}.csv'.format(sheet.name), 'wb') as f:
        writer = csv.writer(f)
        writer.writerows(sheet.row_values(row) for row in range(sheet.nrows))

错误:

Traceback (most recent call last):
  File "C:/Users/datainput.py", line 8, in <module>
    writer.writerows(sheet.row_values(row) for row in range(sheet.nrows))
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 20: ordinal not in range(128)

【问题讨论】:

  • 请添加您的NEW.xlsm的示例
  • 请详细说明您的意思?您的意思是提供所有工作表的名称吗?

标签: python python-2.7 csv xlrd


【解决方案1】:

很明显,处理原始文件中的 unicode 存在问题。 在写入新文件之前,您可以先删除 unicode:

import re
text_without_unicode = re.sub(r'[^\x00-\x7f]', r'', text_with_unicode)

或使用 .encode('utf-8') / decode 函数

【讨论】:

    【解决方案2】:

    我只是想评论一下我遇到了类似的问题,而似乎对我有用的方法正在改变:

    writer.writerows(sheet.row_values(row) for row in range(sheet.nrows))
    

    到:

    writer.writerows([x.encode('utf-8') for x in sheet.row_values(row)] for row in range(sheet.nrows))
    

    (向 Marc vT 提出建议。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多