加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

使用python有条件地从Excel格式化文本字符串

发布时间:2020-12-16 21:38:59 所属栏目:Python 来源:网络整理
导读:我想格式化电子表格(xls或xlsx),以便通过用特定颜色填充背景来格式化包含单词或以某个字符串结尾的任何单元格. 例如,如果单元格包含单词“已删除”,请将其填充为黑色并将文本绘制为白色. 如果单元格以’.pf’结尾,则将单元格绘制为红色. 几年前我发现了类似
我想格式化电子表格(xls或xlsx),以便通过用特定颜色填充背景来格式化包含单词或以某个字符串结尾的任何单元格.

例如,如果单元格包含单词“已删除”,请将其填充为黑色并将文本绘制为白色.
如果单元格以’.pf’结尾,则将单元格绘制为红色.

几年前我发现了类似的问题,提出以下建议:

import xlrd 
import xlutils.copy 

inBook = xlrd.open_workbook('input.xls',formatting_info=True) 
outBook = xlutils.copy.copy(inBook) 

def _getOutCell(outSheet,colIndex,rowIndex): 
    """ HACK: Extract the internal xlwt cell representation. """ 
    row = outSheet._Worksheet__rows.get(rowIndex) 
    if not row: return None 
    cell = row._Row__cells.get(colIndex) 
    return cell 

def setOutCell(outSheet,col,row,value): 
    """ Change cell value without changing formatting. """ 
    # HACK to retain cell style. 
    previousCell = _getOutCell(outSheet,row) 
    # END HACK,PART I 
    outSheet.write(row,value) 
    # HACK,PART II 

    if previousCell: 
        newCell = _getOutCell(outSheet,row) 
    if newCell:
        newCell.xf_idx = previousCell.xf_idx 
    # END HACK 


outSheet = outBook.get_sheet(0) 
setOutCell(outSheet,5,'Test') 
outBook.save('output.xls')

虽然这会将值从input.xls复制到output.xls,但这似乎不会传输格式(打开output.xls时不再格式化input.xls中的测试值,条件格式规则也不会出现在“在excel中管理规则.

“if”数字值的语句似乎有效,但同样,我正在寻找一种格式化包含某些字符串的单元格的方法.谢谢!

解决方法

打开时保留原始input.xls格式:
from xlrd import open_workbook

input_wb = open_workbook('input.xls',formatting_info=True)

基于此模板创建新工作簿:

from xlutils.copy import copy as copy_workbook

output_wb = copy_workbook(input_wb)

定义一些新的单元格样式:

from xlwt import easyxf

red_background = easyxf("pattern: pattern solid,fore_color red;")
black_with_white_font = easyxf('pattern: pattern solid,fore_color black; font: color-index white,bold on;")

评估和修改您的单元格:

input_ws = input_wb.sheet_by_name('StackOverflow')
output_ws = output_wb.get_sheet(0)

for rindex in range(0,input_ws.nrows):
   for cindex in range(0,input_ws.ncols):
       input_cell = input_ws.cell(rindex,cindex)
       if input_cell.value[ input_cell.value.rfind('.'): ] == 'pf':
           output_ws.write(rindex,cindex,input_cell.value,red_background)
       elif input_cell.value.find('deleted') >= 0:
           output_ws.write(rindex,black_with_white_font)
       else:
           pass  # we don't need to modify it

保存新工作簿

output_wb.save('output.xls')

使用上面的示例,未修改的单元格应保持原始格式不变.

如果您需要更改单元格内容并希望保留原始格式(即不使用您的自定义easyxf实例),您可以使用以下代码段:

def changeCell(worksheet,text):
    """ Changes a worksheet cell text while preserving formatting """
    # Adapted from https://stackoverflow.com/a/7686555/1545769
    previousCell = worksheet._Worksheet__rows.get(row)._Row__cells.get(col)
    worksheet.write(row,text)
    newCell = worksheet._Worksheet__rows.get(row)._Row__cells.get(col)
    newCell.xf_idx = previousCell.xf_idx

# ...

changeCell(worksheet_instance,155,2,"New Value")

对于比较,您可以使用字符串方法find和rfind(从右侧搜索).它们返回字符串中子字符串位置的索引.如果未找到子字符串,则返回-1.你会看到上面的input_cell.value.find(‘deleted’)> = 0来评估子字符串’deleted’是否存在.对于.pf比较,我使用了rfind以及Python中的一些名为slicing的东西.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读