【问题标题】:Importing Multiple HTML Files Into Excel as Separate Worksheets将多个 HTML 文件作为单独的工作表导入 Excel
【发布时间】:2018-08-16 05:35:08
【问题描述】:

我有许多 HTML 文件需要打开或导入到单个 Excel 工作簿中,然后简单地保存工作簿。每个 HTML 文件都应位于 Workbook 内自己的 Worksheet 上。

我现有的代码不起作用,它在workbook.Open(html) 行崩溃,并且可能会在以下行崩溃。我无法在网络上搜索特定于该主题的任何内容。

import win32com.client as win32
import pathlib as path


def save_html_files_to_worksheets(read_directory):
    read_path = path.Path(read_directory)
    save_path = read_path.joinpath('Single_Workbook_Containing_HTML_Files.xlsx')

    excel_app = win32.gencache.EnsureDispatch('Excel.Application')
    workbook = excel_app.Workbooks.Add()  # create a new excel workbook

    indx = 1  # used to add new worksheets dependent on number of html files
    for html in read_path.glob('*.html'):  # loop through directory getting html files
        workbook.Open(html)  # open the html in the newly created workbook - this doesn't work though
        worksheet = workbook.Worksheets(indx)  # each iteration in loop add new worksheet
        worksheet.Name = 'Test' + str(indx)  # name added worksheets
        indx += 1
    workbook.SaveAs(str(save_path), 51)  # win32com requires string like path, 51 is xlsx extension
    excel_app.Application.Quit()


save_html_files_to_worksheets(r'C:\Users\<UserName>\Desktop\HTML_FOLDER')

如果有帮助,以下代码可以满足我的一半需求。它将每个 HTML 文件转换为单独的 Excel 文件。我需要一个带有多个工作表的 Excel 文件中的每个 HTML 文件。

import win32com.client as win32
import pathlib as path

def save_as_xlsx(read_directory):
    read_path = path.Path(read_directory)
    excel_app = win32.gencache.EnsureDispatch('Excel.Application')

    for html in read_path.glob('*.html'):
        save_path = read_path.joinpath(html.stem + '.xlsx')
        wb = excel_app.Workbooks.Open(html)
        wb.SaveAs(str(save_path), 51)
    excel_app.Application.Quit()


save_as_xlsx(r'C:\Users\<UserName>\Desktop\HTML_FOLDER')

这里是一个可以使用的示例 HTML 文件的链接,文件中的数据不是真实的:HTML Download Link

【问题讨论】:

  • HTML应该如何插入?作为一个原始字符串进入其中一个单元格?作为Web 浏览器的ActiveX 控件的内容?还有什么?
  • 感谢您的回复。应该插入 HTML 文件,就像您启动 Excel 并在应用程序中打开 HTML 文件一样。每个 HTML 文件本质上都是一个表格,它们具有简单的格式,例如我需要保留的列宽和字体颜色。
  • 如何打开它?尝试在 Excel 2016 中打开 HTML 文件会导致错误提示该文件可能已损坏。
  • 我在原始帖子的最底部添加了一个链接,您可以在其中下载示例 HTML 文件。下载后,启动 Excel 应用程序并转到文件并打开,然后浏览下载的 HTML 文件。
  • 太棒了,谢谢,这个工作。

标签: python html excel python-3.x win32com


【解决方案1】:

一种解决方案是将 HTML 文件打开到临时工作簿中,然后将工作表从那里复制到包含所有这些文件的工作簿中:

workbook = excel_app.Application.Workbooks.Add()
sheet = workbook.Sheets(1)
for path in read_path.glob('*.html'):
    workbook_tmp = excel_app.Application.Workbooks.Open(path)
    workbook_tmp.Sheets(1).Copy(Before=sheet)
    workbook_tmp.Close()
# Remove the redundant 'Sheet1'
excel_app.Application.ShowAlerts = False    
sheet.Delete()
excel_app.Application.ShowAlerts = True

【讨论】:

  • 我喜欢你的方法,我在发布之前尝试过这个,但我想不通。好像你错过了一些东西。例如,xl.Application.ShowAlerts = Falsexl.Application.ShowAlerts = True xl 没有在任何地方定义。我想你的意思是把excel_app。请您提供整个代码库吗?我看到您正在复制它,但是如何将其添加到其他工作簿中?
  • 是的,抱歉,xl 应该是 excel_app。除此之外,这就是全部。 sheet 属于“大”工作簿,因此通过将打开的 HTML 文件复制到“sheet 之前的工作表”,它将在正确的位置结束。
  • 我运行了代码,HTML 文件被复制到的 Excel 文件没有保存在任何地方。因此,当我运行代码时,似乎什么也没发生。此外,您的答案中缺少excel_app = win32.gencache.EnsureDispatch('Excel.Application') 行。
  • excel_appread_path 取自您的原始帖子。同样,保存可以像在您自己的帖子中一样处理。
  • 感谢您的帮助,让我尝试将您给我的内容合并到我的原始帖子中,看看我是否可以让它工作。
【解决方案2】:

我相信pandas 会让你的工作更轻松。

pip install pandas

这是一个示例,说明如何从 wikipedia html 获取多个表并将其输入到 Pandas DataFrame 中并将其保存到磁盘。

import pandas as pd
url = "https://en.wikipedia.org/wiki/List_of_American_films_of_2017"
wikitables = pd.read_html(url, header=0, attrs={"class":"wikitable"})
for idx,df in enumerate(wikitables):
    df.to_csv('{}.csv'.format(idx),index=False)

对于您的用例,这样的事情应该可以工作:

import pathlib as path
import pandas as pd

def save_as_xlsx(read_directory):
    read_path = path.Path(read_directory)

    for html in read_path.glob('*.html'):
        save_path = read_path.joinpath(html.stem + '.xlsx')
        dfs_from_html = pd.read_html(html, header=0,)
        for idx, df in enumerate(dfs_from_html):
            df.to_excel('{}.xlsx'.format(idx),index=False)

** 确保在pd.read_html 函数中设置正确的html 属性。

【讨论】:

  • 我认为 pandas 数据框不会包含任何格式。我无法让pd.read_html() 工作,但我已经使用pd.read_excel() 进行了测试,当我将其保存到新的 Excel 电子表格时,数据框中的所有格式都丢失了。
  • 使用pd.read_html(),我得到以下属性错误:AttributeError: 'list' object has no attribute 'to_excel'
  • 这有点模糊,你能发布你的整个堆栈跟踪吗? df_from_html 应该有 type pandas.core.frame.DataFrame。你能做一个print(type(df_from_html)) 告诉我它说什么吗?
  • 即使我让它工作,我几乎可以肯定它不会在数据框中保留我需要的格式。除非你知道数据框会保留对我来说最重要的字体颜色。我使用 excel 数据框对此进行了测试,并将其复制到另一个 excel 电子表格中,但数据框没有保留格式。
  • 这是您请求的堆栈跟踪:Traceback (most recent call last): File "C:/Users/&lt;UserName&gt;/Documents/PyCharm/PycharmProjects/html_to_excel.py", line 69, in &lt;module&gt; save_as_xlsx(r'C:\Users\&lt;UserName&gt;\Desktop\HTML_FOLDER') File "C:/Users/&lt;UserName&gt;/Documents/PyCharm/PycharmProjects/html_to_excel.py", line 67, in save_as_xlsx df_from_html.to_excel(str(save_path), index=False) AttributeError: 'list' object has no attribute 'to_excel'
【解决方案3】:

这个怎么样?

Sub From_XML_To_XL()
'UpdatebyKutoolsforExcel20151214
    Dim xWb As Workbook
    Dim xSWb As Workbook
    Dim xStrPath As String
    Dim xFileDialog As FileDialog
    Dim xFile As String
    Dim xCount As Long
    On Error GoTo ErrHandler
    Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    xFileDialog.AllowMultiSelect = False
    xFileDialog.Title = "Select a folder [Kutools for Excel]"
    If xFileDialog.Show = -1 Then
        xStrPath = xFileDialog.SelectedItems(1)
    End If
    If xStrPath = "" Then Exit Sub
    Application.ScreenUpdating = False
    Set xSWb = ThisWorkbook
    xCount = 1
    xFile = Dir(xStrPath & "\*.xml")
    Do While xFile <> ""
        Set xWb = Workbooks.OpenXML(xStrPath & "\" & xFile)
        xWb.Sheets(1).UsedRange.Copy xSWb.Sheets(1).Cells(xCount, 1)
        xWb.Close False
        xCount = xSWb.Sheets(1).UsedRange.Rows.Count + 2
        xFile = Dir()
    Loop
    Application.ScreenUpdating = True
    xSWb.Save
    Exit Sub
ErrHandler:
    MsgBox "no files xml", , "Kutools for Excel"
End Sub

【讨论】:

  • 谢谢,但我更喜欢在 Python 中执行此操作,而不是使用 VBA 宏。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-29
  • 2016-04-17
  • 2021-10-24
  • 1970-01-01
  • 1970-01-01
  • 2018-09-08
相关资源
最近更新 更多