Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save Excel as HTML in Python

Tags:

python

excel

I am trying to save an existing Excel file to HTML in Python using win32com.client. Below is my code and the resulting error message. Any suggestions?

import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(r'D:\eclipse\test.xlsx')
excel.Visible = True
ws = wb.Worksheets('Sheet1')
ob = wb.PublishObjects.Add(1,'C:\test.html','Sheet1')
ob.Publish(True)

With the following Traceback:

Traceback (most recent call last):  
File "D:\eclipse\DMS\AGADMS\exceltohtml.py", line 21, in <module>  
ob = wb.PublishObjects.Add(1,'C:\test.html')  
File "C:\Python34\lib\site-packages\win32com\gen_py\00020813-0000-0000-C000-000000000046x0x1x7\PublishObjects.py", line 37, in Add
    , Title)  
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146827284), None)
like image 250
zhang jinxiang Avatar asked Oct 12 '15 05:10

zhang jinxiang


People also ask

Can you use Python to code in Excel?

There are many different Python packages for working with Excel. The majority of these are for reading and writing Excel files (e.g. openpyxl and xlsxwriter). PyXLL is very different to these other packages. Instead of just allowing you to read and write Excel files, PyXLL integrates Python into Excel.


1 Answers

Pandas is very good for this.

Using pandas should simplify this for you. See below:

import pandas as pd 

wb = pd.read_excel('D:\eclipse\test.xlsx') # This reads in your excel doc as a pandas DataFrame

wb.to_html('C:\test.html') # Export the DataFrame (Excel doc) to an html file 

Example Excel input:

Example html output:

Hope this helps.

like image 50
Fletch Avatar answered Oct 16 '22 08:10

Fletch