python - 如何在 Python 中将 Excel 工作表另存为 HTML?

标签 python html vba excel

我正在使用这个库 XlsxWriter .

我打开了一个工作簿并在其中写了一些东西 ( considering the official example ) -

import xlsxwriter

# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('Expenses01.xlsx')
worksheet = workbook.add_worksheet()

# Some data we want to write to the worksheet.
expenses = (
    ['Rent', 1000],
    ['Gas',   100],
    ['Food',  300],
    ['Gym',    50],
)

# Start from the first cell. Rows and columns are zero indexed.
row = 0
col = 0

# Iterate over the data and write it out row by row.
for item, cost in (expenses):
    worksheet.write(row, col,     item)
    worksheet.write(row, col + 1, cost)
    row += 1

# Write a total using a formula.
worksheet.write(row, 0, 'Total')
worksheet.write(row, 1, '=SUM(B1:B4)')

workbook.close()

我已经仔细阅读了文档,但似乎找不到另存为功能。

有没有办法(任何方式)将工作簿保存为HTML文件?

如果无法通过 python 代码实现,我能否以某种方式编写 VBA 代码并从 python 调用该代码?

最佳答案

您可以使用 win32com.client 调用 VBA 宏。假设您的文件名为 Bar...

VBA:

Sub SaveHTML()
ThisWorkbook.SaveAs Filename:="C:\Foo\Bar.htm", FileFormat:=xlHtml
End Sub

python :

from win32com.client import Dispatch

xl = Dispatch('Excel.Application')
xl.Workbooks.Open('C:\Foo\Bar.xlsx')
#xl.Visible = True -- optional
xl.Application.Run("SaveHTML")
xl.Workbooks.Close

根据需要进行修改。

编辑:我忘了补充,使用 win32com 关闭 Excel 绝对是一件痛苦的事情。工作簿将关闭,但应用程序本身将保留(检查任务管理器)。请引用this SO post对此的解决方法。

关于python - 如何在 Python 中将 Excel 工作表另存为 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19631511/

相关文章:

python - Django - Celery 连接被拒绝

javascript - 响应式导航栏切换菜单 jQuery

javascript - 包含空字符串的 HTML 属性不显示 = 运算符

excel - Excel 2010中的形状调整

python - Dialogflow python 客户端版本控制

python - 找到较低级别的模板

html - 嵌套无序列表的 IE 问题

arrays - 长数组 VBA 问题

excel - VBA 自动执行网页抓取进入单元格

python - Scrapy:为什么提取的字符串是这种格式?