繁体   English   中英

Python Openpyxl:如何从列中获取值,append 将其转换为字符串,然后使新字符串成为数组的一部分?

[英]Python Openpyxl: How to take values from a column, append it to a string and then make the new string part of an array?

我正在使用 Python Openpyxl 从 Excel 工作表中提取值,将其存储到数组中,并使用该数组写入新文件。

这是代码;

from openpyxl import load_workbook
workbook = load_workbook(filename="./test.xlsx")

for column in sheet.iter_cols(min_row=2, min_col=1, max_row=300, max_col=1):
    for cell in column:  
        fileNameArray.append(cell.value)

现在,我想创建一个名为 linkArray 的新数组,如下所示;

  1. 如果文件名以 XYZ 以外的任何内容开头,则 fileNameArray 中相应文件名的 linkArray 应为https://www.linkName.com/fileNameArrayValue1
  2. 如果文件名以 XYZ 开头,则 linkArray 应为https://www.differentLinkIfNameStartsWithXYZ/fileNameArrayValue2 等等数百个值。

所以,最后;

linkArray = ['https://www.linkName.com/fileNameArrayValue1', 'https://www.differentLinkIfNameStartsWithXYZ/fileNameArrayValue2'...]

实现这一目标的最佳方法是什么?

谢谢!

扩展你的代码:

from openpyxl import load_workbook
workbook = load_workbook(filename="./test.xlsx")

for column in sheet.iter_cols(min_row=2, min_col=1, max_row=300, max_col=1):
    for cell in column:
        temp = cell.value
        fileNameArray.append(temp)
        if temp.startswith('XYZ'):
            linkArray.append(f'https://www.linkName.com/{temp}')
        else:
            linkArray.append(f'https://www.differentLinkIfNameStartsWithXYZ/{temp}')

或者,如果您要立即填充linkArray

for temp in fileNameArray:
    if temp.startswith('XYZ'):
        linkArray.append(f'https://www.linkName.com/{temp}')
    else:
        linkArray.append(f'https://www.differentLinkIfNameStartsWithXYZ/{temp}')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM