Using xlutils xlwt to copy workbook - python

Is it possible to copy a macros enabled excel workbook? For example, I have:
from xlutils.copy import copy
from xlrd import open_workbook
from tempfile import TemporaryFile
book = open_workbook("book.xlsm")
book_copy = copy(book)
book_copy.save("bookcopy.xlsm")
book_copy.save(TemporaryFile())
However, when I then click on bookcopy.xlsm to open it, I get the following error:
"Excel cannot open the file 'bookcopy.xlsm' because the file format or the file extesion is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."
I don't get this error when I save is as "bookcopy.xls", but I need it to be .xlsm. Does anyone have an idea what the problem is?

Related

Simply opening existing excel files with the excel application already open

With excel already open, at the end of some code I am simply trying to open 2 excel files using the following code. However, nothing loads!
from urllib.request import urlopen
from bs4 import BeautifulSoup
import csv
import datetime
import openpyxl
import time
openPythonQuoteLS = openpyxl.load_workbook('c:\ls_equity\quote\PythonQuoteLS.xlsx')
openQuoteLS = openpyxl.load_workbook('c:\ls_equity\quote\QuoteLS.xlsm')
If all you want to do is open files in Excel, you can just use the OS library to send the command to the OS to open the file, as Aran-Fey mentioned above.
For your specific files:
import os
# ...
os.system('start excel.exe c:\ls_equity\quote\PythonQuoteLS.xlsx')
os.system('start excel.exe c:\ls_equity\quote\QuoteLS.xlsm')

pywintypes.com_error opening Excel with Python

I have the following script which was immitated from here ( http://pythonexcels.com/python-excel-mini-cookbook/ ):
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open('words.xlsx')
and it returns the following error ( full traceback )
Traceback (most recent call last):
File "", line 1, in
wb = excel.Workbooks.Open('words.xlsx')
File "C:directory\Python35\lib\site-packages\win32com\gen_py\00020813-0000-0000-C000-000000000046x0x1x7\Workbooks.py", line 78, in Open
, Converter, AddToMru, Local, CorruptLoad)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "'words.xlsx' could not be found. Check the spelling of the file name, and verify that the file location is correct.\n\nIf you are trying to open the file from your list of most recently used files, make sure that the file has not been renamed, moved, or deleted.", 'xlmain11.chm', 0, -2146827284), None)
When I alternatively use openpyxl's functions to open the workbook there is no issue (referenced this https://automatetheboringstuff.com/chapter12/ ) . The python file and the excel file are in the same folder together. Am I calling something inappropriately?
I am certain that the file is spelled correctly ( words.xlsx ) and that it is in the same folder as the python file.
Any thoughts would be appreciated.
Try this:
import win32com.client as win32
import os
excel = win32.gencache.EnsureDispatch('Excel.Application')
path = os.getcwd().replace('\'','\\') + '\\'
wb = excel.Workbooks.Open(path+'words.xlsx')
Excepted a path error, not module or system error.
'xlmain11.chm' is empty, so don't need this.
Be careful when using escape characters on path-string.
Script and work file are in the same directory!
Hope that helps
Have you tried openpyxl, it's very easy to use, reading and writing excel files is no trouble
from openpyxl import Workbook
And initialize as
wb = Workbook()
ws = wb.active()
And you can start reading and writing right away

Is there a way to edit/save an opening (in excel) xlsx file?

I want to do something like this:
import openpyxl as x
wb = x.load_workbook(filename)
# do some edit to the workbook
wb.save(filename)
The file specified by the filename is opening in Excel. Excel is locking the file so I will get permission denied error running the above code. Is there a way to edit/save it?
from openpyxl import load_workbook
ifile = 'Whales.xlsx'
wb = load_workbook(filename=ifile)
# do some edit to the workbook
wb.save(ifile)

saving an existing worksheet as html in python

I went through these link and other links for xlwt, xlrd and xlutils
writing to existing workbook using xlwt
from xlutils.copy import copy
from xlrd import open_workbook
from xlwt import easyxf
rb = open_workbook('example.xls',formatting_info=True)
r_sheet = rb.sheet_by_index(0)
print r_sheet
print r_sheet.name
wb = copy(rb)
w_sheet = wb.get_sheet(0)
print w_sheet.name
w_sheet.save('example.html') #it throws an error in the last line saying "AttributeError: 'Worksheet' object has no attribute 'save'"
How can I save the worksheet alone as HTML file uing python
I am not sure you can save and excel sheet as html just with xlwt or xlrd.
One alternative is to use pandas which internally uses xlrd and xlwt saving you of coding all the steps involved.
You can read your excel sheet with
df = pandas.read_excel('example.xls', sheetname='sheet1')
and get it as html with:
html = df.to_html()
html is a string you can save in a file with open(myfile, 'w').write(html)

Issues with excel file. XLRDError: Unsupported format, or corrupt file: What kind of file is this?

I have a bit of code that works with an xls file. It works for everything I've thrown at it except this one file and I don't know how to properly identify what this one file is. I get the file off of a website I am navigating with Selenium. This particular spreadsheet always downloads as a file type that causes this error.
The full error is:
Traceback (most recent call last):
File "/Users/Meir/Documents/PYTHON/IFG User Update/code/ifg_TPA_update_excel.py", line 44, in <module>
rb = open_workbook((os.path.expanduser("~/Documents/PYTHON/Selenium test/TPA_Example.xls")),formatting_info=True)
File "/usr/local/lib/python2.7/site-packages/xlrd/__init__.py", line 443, in open_workbook
ragged_rows=ragged_rows,
File "/usr/local/lib/python2.7/site-packages/xlrd/book.py", line 94, in open_workbook_xls
biff_version = bk.getbof(XL_WORKBOOK_GLOBALS)
File "/usr/local/lib/python2.7/site-packages/xlrd/book.py", line 1262, in getbof
bof_error('Expected BOF record; found %r' % self.mem[savpos:savpos+8])
File "/usr/local/lib/python2.7/site-packages/xlrd/book.py", line 1256, in bof_error
raise XLRDError('Unsupported format, or corrupt file: ' + msg)
XLRDError: Unsupported format, or corrupt file: Expected BOF record; found '\xff\xfe<\x00S\x00T\x00'
The file I am trying to open displays as an xls file in my finder. However, when I open it, it does not open with the file name as the header but rather displays "Workbook1". When I hit save, it opens the save menu as if I had clicked save as, and defaults to "Workbook1.xlsx". I tried changing my code to open it as an xlsx file, but then it errors out saying it cannot find the file. Whenever I try googling it, I don't know how to phrase it to get a relevant answer.
When I contacted the websites support team asking what kind of file the TPA bulks op sheet is they replied:
The TPA bulk ops is an older version than the rest of the bulk ops, it's due to be rebuilt some time later this year. When downloading the file your best bet is to do a Save As and save it as an older version of .xls, I usually select Microsoft Excel 5.0/95 Workbook, and also format it as text. Formatted that way it should upload without issue.
Any ideas as to how I can open this right from Python?
Currently I am building each part as a separate code and I was going to combine them all together once I get it sorted out. The below is the section of code that will be opening the file and is experiencing the error.
My code:
#!/usr/bin/env python
## Import OS and Modules
import os
import csv
import xlrd
import xlwt
import xlutils
import csv
import collections
## Define Input File from IFG
ifg_user_file = "New_PCs_to_set_up_in_marketing_database_-_4-11-2013.csv"
## Import data
data = [row for row in csv.reader(open (os.path.expanduser("~/Downloads/" + ifg_user_file),'U'))]
## Find number of rows
row_count = sum(1 for row in data)
print row_count
## Set to turn off when reaching the end of data
end_of_data = False
from xlutils.copy import copy # http://pypi.python.org/pypi/xlutils
from xlrd import open_workbook # http://pypi.python.org/pypi/xlrd
from xlwt import easyxf # http://pypi.python.org/pypi/xlwt
##################################################################################
## THE ERROR OCCURS AT THE LINE BELOW
rb = open_workbook((os.path.expanduser("~/Documents/PYTHON/Selenium test/TPA_Example.xls")),formatting_info=True)
r_sheet = rb.sheet_by_index(0) # read only copy to introspect the file
EDIT: I tried to open it with codecs rather than open for diagnostics
rb=codecs.open((os.path.expanduser("~/Documents/PYTHON/Selenium test/TPA_Example.xls")), 'r', encoding='utf16');
print rb;
print rb.readline();
print rb.read(20);
It printed the following result:
<open file '/Users/Meir/Documents/PYTHON/Selenium test/TPA_Example.xls', mode 'rb' at 0x110fe51e0>
<STYLE>
.excel { BORDER-RIGHT: black 1px solid; BORDER-TOP: black 1px solid; BORDER-LEFT: black 1px so
It looks like it is an excel document then. Not sure how to proceed. Is there a universal open an excel document command?

Categories