如何使用Python openpyxl将文本文件的特定部分复制到Excel工作表中的特定单元格?

2024-04-19 07:08:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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 number行)。我写不出代码的第二部分。你能帮帮我吗?在


Tags: pathruninnumberforifwsline
1条回答
网友
1楼 · 发布于 2024-04-19 07:08:10
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)

相关问题 更多 >