繁体   English   中英

Python将Excel合并为CSV Unicode问题

[英]Python Merging Excel to CSV Unicode issue

我在这里有一些示例代码,其中我正在使用openpyxl库将目录中的所有.xlsx文件转换为.csv文件...但是我遇到了'AttributeError:'NoneType'对象没有属性'encode ''-如何调整下面的代码,如果它是NoneType,则cell.value不会得到编码? 谢谢。

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])

好像您是在一个空单元格上调用encode() 您可能需要添加一些内容来检查您要添加的单元格是否为无值,并提供一个您希望其包含的替代值来表示单元格的不存在/空/无。

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)

但是为了使您的列表理解更加美观,我们可以改为执行以下操作:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM