如何在Excel文档单元格中找到文本子集的格式

时间:2012-09-11 14:15:38

标签: python xlrd

使用Python,我需要在给定的Excel工作表单元格中找到粗体或斜体的所有子字符串。

我的问题与此类似:

Using XLRD module and Python to determine cell font style (italics or not)

..但该解决方案不适用于我,因为我无法假设相同格式适用于单元格中的所有内容。单个单元格中的值可能如下所示:


1。一些粗体文字一些普通文字。 一些斜体文字


有没有办法使用xlrd(或任何其他Python Excel模块)查找单元格中一系列字符的格式?

3 个答案:

答案 0 :(得分:7)

xlrd可以做到这一点。您必须使用kwarg load_workbook()调用formatting_info=True,然后工作表对象将具有属性rich_text_runlist_map,这是一个字典映射单元格坐标((row, col)元组)到运行列表该单元格。运行列表是(offset, font_index)对的序列,其中offset告诉您字体在单元格中的开始位置,font_index索引到工作簿对象的font_list属性(工作簿对象是load_workbook())返回的内容,它为您提供了描述字体属性的Font object,包括粗体,斜体,字体,大小等。

答案 1 :(得分:6)

感谢@Vyassa所有正确的指针,我已经能够编写以下代码,它迭代XLS文件中的行并输出具有“单一”样式信息的单元格的样式信息(例如,整个细胞是斜体)或样式“细分”(例如,细胞的一部分是斜体,部分细胞不是斜体)。

import xlrd

# accessing Column 'C' in this example
COL_IDX = 2

book = xlrd.open_workbook('your-file.xls', formatting_info=True)
first_sheet = book.sheet_by_index(0)

for row_idx in range(first_sheet.nrows):
  text_cell = first_sheet.cell_value(row_idx, COL_IDX)
  text_cell_xf = book.xf_list[first_sheet.cell_xf_index(row_idx, COL_IDX)]

  # skip rows where cell is empty
  if not text_cell:
    continue
  print text_cell,

  text_cell_runlist = first_sheet.rich_text_runlist_map.get((row_idx, COL_IDX))
  if text_cell_runlist:
    print '(cell multi style) SEGMENTS:'
    segments = []
    for segment_idx in range(len(text_cell_runlist)):
      start = text_cell_runlist[segment_idx][0]
      # the last segment starts at given 'start' and ends at the end of the string
      end = None
      if segment_idx != len(text_cell_runlist) - 1:
        end = text_cell_runlist[segment_idx + 1][0]
      segment_text = text_cell[start:end]
      segments.append({
        'text': segment_text,
        'font': book.font_list[text_cell_runlist[segment_idx][1]]
      })
    # segments did not start at beginning, assume cell starts with text styled as the cell
    if text_cell_runlist[0][0] != 0:
      segments.insert(0, {
        'text': text_cell[:text_cell_runlist[0][0]],
        'font': book.font_list[text_cell_xf.font_index]
      })

    for segment in segments:
      print segment['text'],
      print 'italic:', segment['font'].italic,
      print 'bold:', segment['font'].bold

  else:
    print '(cell single style)',
    print 'italic:', book.font_list[text_cell_xf.font_index].italic,
    print 'bold:', book.font_list[text_cell_xf.font_index].bold

答案 2 :(得分:3)

我不知道您是否可以使用xlrd执行此操作,但由于您询问任何其他Python Excel模块:openpyxl 无法在版本1.6中执行此操作。 1。

富文本在get_string()中的函数openpyxl/reader/strings.py中重新构建。在该模块中使用“原始”字符串设置第二个表格会相对容易。