Python write to spreadsheet?
Tim Chase
python.list at tim.thechases.com
Sat May 30 08:24:22 EDT 2015
On 2015-05-30 10:30, Justin Thyme wrote:
> Is it possible to write a Python program that will start MS Excel,
> create a spreadsheet and fill cells A1 to A10 (say) with the data
> in a Python array? The answer is surely yes, but is there an
> outline of how to do it somewhere?
it depends on how strictly you want to keep your order of operations.
You *can* use Windows API calls to automate Excel, instructing it to
create a new sheet, then populate the various cells with data.
However, this is fragile, Windows-specific, and requires the target
to have Excel on their machine.
If you're willing to forego your specified ordering and create a
file, then open it in Excel, you can use the add-on xlrd/xlwt packages
(the former reads, the latter writes) to write XLS files that you can
then open in Excel.
Finally, if you're going down that route, the *easiest* way is to
simply use Python's csv module from the standard library.
import csv
FILENAME = "out.csv"
with open(FILENAME, 'wb') as f:
w = csv.writer(f)
for item in data:
w.writerow([
item,
#, "" # optionally add a blank column because
# some parsers like csv.Sniffer will notice
# the lack of commas and try to find the most
# common repeated string
])
You can then launch that file in Excel, or even better, whatever the
registered program is:
import os, sys, subprocess
def open_file(filename):
if sys.platform == "win32":
os.startfile(filename)
else:
if sys.platform == "darwin":
program = "open"
else:
program = "xdg-open"
subprocess.call([program, filename])
open_file(FILENAME)
-tkc
More information about the Python-list
mailing list