如何在Excel中将Excel Sheet作为HTML保存? [英] How do I save Excel Sheet as HTML in Python?

查看:552
本文介绍了如何在Excel中将Excel Sheet作为HTML保存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此图书馆 XlsxWriter

我已经打开了一本工作簿,并写了一些内容(考虑到官方示例) -

I've opened a workbook and written some stuff in it (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()

我经历了严格的文档,但似乎找不到保存作为功能。

I've gone through the docs rigorously but can't seem to find the save as functionality.

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

Is there a way (any way) to save the workbook as a HTML file?

如果从python代码是不可能的,我可以以某种方式写 VBA 代码,并从python调用该代码?

If it isn't possible from python code, can I somehow write VBA code and call that code from python?

推荐答案

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

You can use win32com.client to call a VBA macro. Assuming your file is named 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绝对的痛苦。工作簿将关闭,但应用程序本身将停留(检查任务管理器)。请参阅此SO发布解决方法。

I forgot to add, using win32com to close Excel is an absolute pain. The workbooks will close, but the application itself will linger (check Task Manager). Please refer to this SO post on a workaround for this.

这篇关于如何在Excel中将Excel Sheet作为HTML保存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆