[英]Python Merging Excel to CSV Unicode issue
I have some sample code here in which I'm using the openpyxl library to convert all the .xlsx files in a directory to a .csv file...however I am getting a 'AttributeError: 'NoneType' object has no attribute 'encode'' - how can I adjust the code below so the cell.value is not getting encoded if it is NoneType? 我在这里有一些示例代码,其中我正在使用openpyxl库将目录中的所有.xlsx文件转换为.csv文件...但是我遇到了'AttributeError:'NoneType'对象没有属性'encode ''-如何调整下面的代码,如果它是NoneType,则cell.value不会得到编码? Thanks.
谢谢。
import openpyxl
import csv
from glob import glob
with open('All.csv', 'ab') as f:
for filename in sorted(glob("*.xlsx")):
wb = openpyxl.load_workbook(filename)
sh = wb.get_active_sheet()
with open('All.csv', 'ab') as f:
c = csv.writer(f)
for r in sh.rows:
c.writerow([cell.value.encode("utf-8") for cell in r])
您需要显式测试None
并使用替代项,可能是一个空字符串。
c.writerow([b'' if cell is None else cell.value.encode("utf-8") for cell in r])
Looks like you're calling encode()
on an empty cell. 好像您是在一个空单元格上调用
encode()
。 You might need to add something to check if cell you're trying to add is none value and offer an alternative value you want it to include to represent nonexistence/emptiness/noneness of a cell: 您可能需要添加一些内容来检查您要添加的单元格是否为无值,并提供一个您希望其包含的替代值来表示单元格的不存在/空/无。
for r in sh.rows:
newrow = []
for cell in r:
if cell.value:
newrow += cell.value.encode("utf-8")
elif cell.value == None:
newrow += ''
c.writerow(newrow)
but to keep the niceness of your list comprehension in place we could instead you the following: 但是为了使您的列表理解更加美观,我们可以改为执行以下操作:
for r in sh.rows:
c.writerow([cell.value.encode("utf-8") if cell.value is not None else '' for cell in r])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.