首页 > 解决方案 > 逗号分隔的字符串用python excel单元格

问题描述

我想将字符串中的内容推送到 xls 内容是

abc,[1,2],abc/er/t_y,def,[3,4],def/er/t_d,ghi,ghi/tr/t_p,jkl,[5],jkl/tr/t_m_n,nop,nop/tr/t_k

这是我的示例代码(使用 xlwt)

workbook = xlwt.Workbook()
sh = workbook.add_sheet("Sheet1")
def exporttoexcel ():  
    print("I am in print excel")
    rowCount = 1
    for row in finalvalue:  # in finalvalue abc,[1,2],abc/er/ty.. is stored as type= str
        colCount = 0
        for column in row.split(","):  
            sh.write(rowCount, colCount, column)
            colCount += 1
        rowCount += 1
    workbook.save("myxl.xls")

exporttoexcel()

在 excel 中摄取数据时,需要遵循的规则很少

- column headers are main,ids,UI
- each cell have one value except ids [ids may or may not be there]
- after three columns it should move to the next row
- the second column i.e **id** should have only ids and if not available it should be kept as blank

如何将数据推送到与上述规则类似的excel中?

 | A  | B | C |
1|main|ids|UI|
2|abc |1,2|abc/tr/t_y|
3|def |3,4|def/tr/t_d|
4|ghi |   |ghi/tr/t_p|
5|jkl |5  |jkl/tr/t_m_n|
6|nop |   |nop/tr/t_k|

标签: pythonexcelopenpyxlxlsxwriterxlwt

解决方案


使用正则表达式检查带有 [] 的值

import re
m = re.search(r"\[(\w+)\]", column)


推荐阅读