Openpyxl Unicode 值

Ste*_*aly 7 python unicode openpyxl

我正在使用openpyxl从 Excel 电子表格中读取单元格值。其中一个单元格的值由换行符分隔。我想使用换行符作为分隔符来分割字符串。然而,似乎openpyxl是将回车序列化为非标准格式。看看下面的例子。

代码

import openpyxl

# Open the worksheet
wb = openpyxl.load_workbook(wb_path)
ws = wb.get_sheet_by_name("testing")

# Get the string value
tests_str = ws.cell(row = row, column = column).value

# Split text on newlines and add them to the list
tests = []
for test in tests_str.splitlines():
    tests.append(test)
Run Code Online (Sandbox Code Playgroud)

输出

>>> tests_str
u'Test1_x000D_\nTest2_x000D_\nTest3_x000D_'
>>> tests
[u'Test1_x000D_', u'Test2_x000D_', u'Test3_x000D_']
Run Code Online (Sandbox Code Playgroud)

openpyxl似乎正在将\r字符序列化,_x000D_这就是为什么splitlines()不将其作为换行符删除的原因。有这样的openpyxl行为的原因吗?难道我做错了什么?

twi*_*337 9

正如2015 年的一些支持问题请参阅 Google 缓存条目以避免登录)中所述,该问题已发布在 openpyxl 的官方 Bitbucket 项目中,这是由 Excel 完成的,并且似乎对 openpyxl 失去了控制。

为了解决这个问题,有一些用于编码/解码的实用函数

>> openpyxl.utils.escape.unescape(tests_str))
u'Test1\r\nTest2\r\nTest3\r'
Run Code Online (Sandbox Code Playgroud)

文档链接:https://openpyxl.readthedocs.io/en/stable/api/openpyxl.utils.escape.html


Mar*_*nen 5

看起来 openpyxl 或 Excel 正在\r以这种方式编码回车符( , ASCII 0Dh)。您也可以将它们转换回来或拆分它们:

>>> s=u'Test1_x000D_\nTest2_x000D_\nTest3_x000D_'
>>> s.split('_x000D_\n')
[u'Test1', u'Test2', u'Test3_x000D_']     # This misses the final one.
>>> s.replace('_x000D_','').splitlines()  # Better...
[u'Test1', u'Test2', u'Test3']
Run Code Online (Sandbox Code Playgroud)

  • Excel 进行编码,openpyxl 保留它。 (2认同)