Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将xlsm转换为csv_Python_Python 2.7_Csv_Xlrd - Fatal编程技术网

Python 将xlsm转换为csv

Python 将xlsm转换为csv,python,python-2.7,csv,xlrd,Python,Python 2.7,Csv,Xlrd,我正在解析vba宏加密的Excel文件,并试图复制Excel文件中的所有工作表,但我的脚本不断崩溃。在我的代码片段中,我做错了什么 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(

我正在解析vba宏加密的Excel文件,并试图复制Excel文件中的所有工作表,但我的脚本不断崩溃。在我的代码片段中,我做错了什么

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)
回溯(最近一次呼叫最后一次):
文件“C:/Users/datainput.py”,第8行,在
writer.writerows(sheet.row\范围(sheet.nrows)中的行的值(row))
UnicodeEncodeError:“ascii”编解码器无法对位置20处的字符u'\u2013'进行编码:序号不在范围内(128)

很明显,在处理原始文件中的unicode时存在一个问题。 在写入新文件之前,您可以考虑使用删除unicode:

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

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

我只是想评论一下,我遇到了类似的问题,似乎对我有用的东西正在发生变化:

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


(为Marc vT提供建议的道具。)

请添加您的
新.xlsm的示例请详细说明您的意思?你的意思是提供所有工作表的名称吗?
writer.writerows([x.encode('utf-8') for x in sheet.row_values(row)] for row in range(sheet.nrows))