我们正在努力完成从Python 2.7到Python 3.5的工作转换。这是公司范围内的变化,我们大部分当前的脚本都是用2.7编写的,没有其他的库。我利用了我们正在使用的Anaconda发行版,并且已经使用了2to3模块或完全重写了大部分的脚本。不过还有一段代码卡住了我,我没有写过,原始作者也不在现场。他也没有提供注释,所以我只能猜测脚本的全部内容。95%的脚本正常运行,直到最后它创建了七个不同解析数据的CSV文件,然后有一个自定义函数将CSV文件合并为一个XLS工作簿,每个CSV作为新选项卡。
import csv
import xlwt
import glob
import openpyxl
from openpyxl import Workbook
Parsefiles = glob.glob(directory + '/' + "Parsed*.csv")
def xlsmaker():
for f in Parsefiles:
(path, name) = os.path.split(f)
(chort_name, extension) = os.path.splittext(name)
ws = wb.add_sheet(short_name)
xreader = csv.reader(open(f, 'rb'))
newdata = [line for line in xreader]
for rowx, row in enumerate(newdata)
for colx, value in enumerate(row):
if value.isdigit():
ws.write(rowx, colx, value)
xlsmaker()
for f in Parsefiles:
os.remove(f)
wb.save(directory + '/' + "Finished" + '' + oshort + '' + timestr + ".xls")
这段代码完全使用 Python 2.7 编写,并在 Python 2.7 中运行正常。但是,在 Python 3.5 中运行时会报错。
File "parsetool.py", line 521, in (module)
xlsmaker()
File "parsetool.py", line 511, in xlsmaker
ws = wb.add_sheet(short_name)
File "c:\pythonscripts\workbook.py", line 168 in add_sheet
raise TypeError("The paramete you have given is not of the type '%s'"% self._worksheet_class.__name__)
TypeError: The parameter you have given is not of the type "Worksheet"
针对上述错误,有什么解决方法吗?我已经尝试了多次重写,但是出现了类似的错误或新的错误。我正在考虑采用全新的方法创建xls文件,可能使用pandas。
pandas
假定openpyxl
可用。您能否让这个答案更完整一些?(我从 miniconda 开始,如果这解释了为什么我没有安装所有内容。) - r2evansNameError: name 'xlsxwriter' is not defined
出问题了,因为需要按名称发送。你正在发送一个模块。正确的行是:writer = pd.ExcelWriter('yourfile.xlsx', engine='xlsxwriter')
请将 'xlsxwriter' 作为字符串发送。 - hecvdpip install openpyxl
才能让它工作。似乎 pandas 不会为您完成此部分。 - Stabledogwriter.save()
的Pandas警告,则答案是改为使用writer作为上下文管理器。完整示例 - Christian Long