【问题标题】:How to copy a specific portion of text file to a specific cell in excel worksheet with python openpyxl?如何使用python openpyxl将文本文件的特定部分复制到excel工作表中的特定单元格?
【发布时间】:2017-06-23 20:48:54
【问题描述】:
import openpyxl

## open the specific output file 

with open('/Users/bekir/Desktop/Python_project/Output/r391.txt') as
wb:
    lines = wb.read().splitlines()

## find tht from output file

for line in lines[8400:8480]:
    if line.startswith('       top-water-inlet temp       ='):
        THT = line.split('=',1)[-1].strip()[0:6]

for line in lines[1:30]:
    if line.startswith('  Geometry file :'):
        run_number = line.split(':',1)[-1].strip()[0:4]

## write THT into a specific cell of excel worksheet      

file_path  = '/Users/bekir/Desktop/deneme.xlsx'
xfile = openpyxl.load_workbook(file_path)
ws = xfile['Sheet3']

# have to start range from 1 since excel cell offset starts at 1
for i in range(1,100):
    cell = 'C' + str(i)

    if ws[cell].value == run_number:
        ws['J' + str(i)] = THT
        break

xfile.save(file_path)

你好,

我可以找到文本文件的特定部分,但无法使用 openpyxl (python2.7) 复制到 Excel 工作表的特定单元格中。程序必须匹配工作表中的run_number(已经写在工作表中)并将THT值写入坐标('J'列&run numbers行)。我无法编写代码的第二部分。请你帮助我好吗?

【问题讨论】:

    标签: python openpyxl


    【解决方案1】:
    file_path  = '/Users/bekir/Documents/deneme.xlsx'
    xfile = openpyxl.load_workbook(file_path)
    ws = xfile['sayfa3']
    
    # have to start range from 1 since excel cell offset starts at 1
    for i in range(1,100):
        cell = 'D' + str(i)
    
        if ws[cell].value == run_number:
            ws['D' + str(i)] = THT
            break
    
    xfile.save(file_path)
    

    【讨论】:

    • /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/openpyxl/reader/worksheet.py:310: UserWarning: Unknown extension is not supported and will被删除 warn(msg) 。 @Alex 为什么我会收到这条消息?
    • @BekirAydin 请查看我更新的代码,因为这将起作用。我对此进行了正确的测试,没有任何问题。
    • 感谢您的帮助@Alex!经过小幅修正后,它运行良好。我编辑了顶部的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 2022-11-20
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    相关资源
    最近更新 更多