【发布时间】:2016-05-01 03:11:11
【问题描述】:
我正在尝试编写一个接收 .xlsx 输入并输出 json 的基本 Python 脚本。我的其中一个电子表格的结构很奇怪。也就是说,在 C 列的每个单元格中,都有一个字符串需要分成两列。唯一构成需要分离的部分的是它们的字体不同。所以,例如:
"this is in Arial this is in Times"
我目前的脚本如下:
# Import Libraries
from openpyxl import load_workbook
from openpyxl.styles import Font
import sys
import json
# Load argv[1] as workbook
wb = load_workbook(sys.argv[1])
ws = wb.active
# Create wordlist
wordList = []
# Loop through rows in worksheet, create if statements for different columns and append Lemmas to wordList.
for entry in ws.iter_rows('A2:C3'):
newLemma = {"word":[], "definition":[]}
for col in entry:
if col.column == 'A':
newLemma["word"].append(col.value)
if col.column == 'B':
newLemma["definition"].append(col.value)
wordList.append(newLemma)
# create json
json = json.dumps(wordList)
# write to new file
textfile = open('wordlist.json','wb')
textfile.write(json)
textfile.close()
现在,我需要的是以下内容:
if col.column == 'C':
if col.font.name == "Arial"
...append(col.value)
if col.font.name == "Times"
...append(col.value)
不幸的是,col.font.name 只给出分配给整个单元格的字体,而不是分配给单元格内的字符串。因此,如果为单元格分配了 Arial 字体,即使有一半的单词是 Times,col.font.name 仍然会产生 Arial。
如果我使用col.value.split(" ") 遍历单元格中的每个单词,然后尝试打印 font.name,我会收到一条 AttributeError 消息,指出 'unicode' 对象没有属性 'font'。
有没有办法使用 openpyxl 或其他 Python 库来做到这一点?或者,有没有办法使用excel宏根据字体类型将一列分成两列?我对这里的任何解决方案都持开放态度,因为必须在每个单元格中手动输入分隔字符会很痛苦。
【问题讨论】:
-
你能从一个单元格中转储数据吗?也许使用二进制格式?
-
我认为你应该使用 XLSXWriter。
标签: python excel vba fonts openpyxl