hi all, 
 
thanks for this sharing. when i copy and run this code, i got this error:
 
Traceback (most recent call last):
  File "C:/Python25/myscript/excel/sampleexcel.py", line 1, in <module>
    import csv
  File "C:/Python25/myscript/excel\csv.py", line 3, in <module>
    w=csv.writer(open('output.csv','w'))
AttributeError: 'module' object has no attribute 'writer'
 
i'm using Python 2.5 and Win XP. pls help advise. 
 
thanks
tcl
 


Date: Wed, 11 May 2011 14:05:12 +0100
From: wpr...@gmail.com
To: taxbot...@gmail.com
CC: tutor@python.org
Subject: Re: [Tutor] create an xls file using data from a txt file




On 11 May 2011 03:57, tax botsis <taxbot...@gmail.com> wrote:

I tried to work that out with xlwt but couldn't. Actually, I started working on 
the following script but I couldn't even split the line for further processing:



OK, I've thrown together a quick sample demonstrating all the concepts you need 
(obviously you need to take from this what is relevant to you): 

import csv
import xlwt
import os
import sys

# Look for input file in same location as script file:
inputfilename = os.path.join(os.path.dirname(sys.argv[0]), 'tabdelimited.txt')
# Strip off the path
basefilename = os.path.basename(inputfilename)
# Strip off the extension
basefilename_noext = os.path.splitext(basefilename)[0]
# Get the path of the input file as the target output path
targetoutputpath = os.path.dirname(inputfilename)
# Generate the output filename
outputfilename =  os.path.join(targetoutputpath, basefilename_noext+'.xls')
 
# Create a workbook object
workbook = xlwt.Workbook()
# Add a sheet object
worksheet = workbook.add_sheet(basefilename_noext, cell_overwrite_ok=True)

# Get a CSV reader object set up for reading the input file with tab delimiters
datareader = csv.reader(open(inputfilename, 'rb'),
                        delimiter='\t', quotechar='"')

# Process the file and output to Excel sheet
for rowno, row in enumerate(datareader):
    for colno, colitem in enumerate(row):
        worksheet.write(rowno, colno, colitem)

# Write the output file.
workbook.save(outputfilename)

# Open it via the operating system (will only work on Windows)
# On Linux/Unix you would use subprocess.Popen(['xdg-open', filename])
os.startfile(outputfilename)


The code is also available at the following URL in case the formatting gets 
eaten by the mail system: http://pastebin.com/APpM7EPf

Regards

Walter 

_______________________________________________ Tutor maillist - 
Tutor@python.org To unsubscribe or change subscription options: 
http://mail.python.org/mailman/listinfo/tutor                                   
 
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to