将格式化的 HTML 逐行插入 Excel 工作表

问题描述 投票:0回答:1

我有一个相当奇怪的用例,我无法解决。我已格式化 HTML 代码(即带有彩色文本的 HTML),我希望保留其格式并将其粘贴到指定工作表上的 Excel 中。这些文档可能相当长(例如几百行),因此将它们放入一个大单元格中并不是一个真正可行的选择(尽管我也尝试过但无法使其工作),而且我认为逐行可能是最好的路线。

我一直在尝试这个,但似乎 xlwings 只会尊重 xlwings 的剪贴板;即 pyperclip 将其复制到剪贴板,但粘贴失败,因为 xlwings 无法识别剪贴板上的任何内容(换句话说,如果您之前立即执行 .copy,它可以工作,但它没有我需要的数据! )

寻求任何帮助。这只是文本,而不是 HTML 表格。我确实知道并认识到这是一个奇怪的用例,但事实就是如此......

import xlwings as xl
import pyperclip

wb = xl.Book()

#read in html to string
with open('Output.html', 'r') as file:
    data = file.read()

#wb.sheets("Sheet1").range("A1").copy()    #this prevents the error, but doesn't have the data I need. Proves xlwings doesn't respect the pyperclip clipboard
wb.sheets("Sheet1").range("A1").paste() #fails since xlwings doesn't respect pyperclip clipboard```
python excel xlwings pyperclip
1个回答
0
投票

为什么不直接读取数据并逐行写入工作表?

import xlwings as xl


#read in html to string
with open('Output.html', 'r') as file:
    #data = file.read()
    data = file.readlines()  # Html lines as separate lines

with xl.App(visible=False) as app:
    wb = xl.Book()

    ### Write each line to the next row in the Sheet down Column A
    for row, line in enumerate(data, 1):
        wb.sheets("Sheet1").range(f'A{row}').value = line
        wb.sheets("Sheet1").range(f'A{row}').api.WrapText = False

    wb.save('Output.xlsx')
© www.soinside.com 2019 - 2024. All rights reserved.