<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Python Excels &#187; Uncategorized</title>
	<atom:link href="http://www.pythonexcels.com/category/uncategorized/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.pythonexcels.com</link>
	<description>Data Mining with Excel and Python</description>
	<lastBuildDate>Mon, 08 Feb 2010 03:56:05 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>A User Friendly Experience</title>
		<link>http://www.pythonexcels.com/2010/02/a-user-friendly-experience/</link>
		<comments>http://www.pythonexcels.com/2010/02/a-user-friendly-experience/#comments</comments>
		<pubDate>Mon, 08 Feb 2010 03:56:05 +0000</pubDate>
		<dc:creator>dan</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.pythonexcels.com/?p=263</guid>
		<description><![CDATA[Let&#8217;s be honest for a second, when was the last time you saw a Windows user running something from the command prompt?   Well, I do it occasionally, but I can&#8217;t say I remember seeing a non-IT person using the command prompt recently.  So if you&#8217;re going to offer your users a Windows [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s be honest for a second, when was the last time you saw a Windows user running something from the command prompt?   Well, I do it occasionally, but I can&#8217;t say I remember seeing a non-IT person using the command prompt recently.  So if you&#8217;re going to offer your users a Windows program, you better give them an icon to click and let them drag stuff onto it.  And if something goes wrong, you better have a decent error message.  This post will take the Pivot Table generation script developed in the <a href="http://www.pythonexcels.com/2009/12/extending-pivot-table-data/">last post</a> and turn it into a user friendly Windows program with better flexibility and improved user experience.  </p>
<p>The scripts developed previously could be run at the command line or by double clicking on the icon for the script line this.</p>
<p><img src="http://www.pythonexcels.com/wp-content/uploads/2010/02/20100207_commandexe1.png" alt="20100207_commandexe" title="20100207_commandexe" width="470" height="155" class="alignnone size-full wp-image-264" /></p>
<p><img src="http://www.pythonexcels.com/wp-content/uploads/2010/02/20100207_erpicon.png" alt="20100207_erpicon" title="20100207_erpicon" width="157" height="134" class="alignnone size-full wp-image-265" /></p>
<p>This works because the input file name, ABCDCatering.xls, is hard coded within the script.  In the real world, your users will have folders containing dozens of randomly named spreadsheets.  If a user accidentally provides a corrupt spreadsheet, the program should keep cranking through the other files and let the user recover the damaged file later.  The script developed in the last post will need some enhancements to make it more user friendly, including:</p>
<ul>
<li>Provide support for multiple randomly named input spreadsheets</li>
<li>Add some simple message boxes and drag-and-drop support</li>
<li>Improve the error checking and error recovery to give the user feedback when something goes wrong</li>
</ul>
<p>To keep things concise, this version of the script only allows the user to run the program by dragging and dropping files onto the program icon.   Enhancing the script to also support command line operation is left as an exercise for the user. Let&#8217;s work through each of the usability issues below: </p>
<p><strong>Multiple File Support</strong><br />
As I mentioned, Windows XP/Vista/7 users typically don&#8217;t interact with the command prompt. Instead, programs are run by clicking on their icons, either from the desktop, a folder, or the Start menu.  A user specifies spreadsheets or document files by opening them in the application or dragging them onto the program icon on the desktop or in the Explorer window. You can also add the file names after the program name at the command prompt if needed. </p>
<p>To process multiple files, the program needs to process command line args, which are already conveniently available in the <code>sys.argv</code> list. Note that the first argument <code>sys.argv[0]</code> is used for the script name.  The <code>runexcel</code> function is modified to pass sys.argv to the runexcel function, which loops through each of the input files.</p>
<pre class="brush: python; first-line: 222">
if __name__ == "__main__":
    runexcel(sys.argv)
</pre>
<pre class="brush: python; first-line: 69">
for fname in args[1:]:
    # Process spreadsheet files
</pre>
<p>The <code>for</code> loop wraps the <code>wb = excel.Workbooks.Open(fname)</code> call, the <code>wb.SaveAs()</code> call, and everything in between so each workbook is processed within the loop.  After the loop finishes, a check for errors is made.  If any errors occurred a warning and message box are issued. </p>
<p><strong>Primitive GUI Support</strong><br />
Adding message boxes and providing basic drag-and-drop support adds a level of familiarity for Windows users.  Python supports a large number of GUI frameworks, see <a href="http://wiki.python.org/moin/GuiProgramming">http://wiki.python.org/moin/GuiProgramming</a> for a comprehensive list.  Building a complete graphic interface for this script is beyond the scope of this article, and isn&#8217;t really necessary anyway.  Instead, you can add support for simple message boxes using the MessageBoxA function built into Windows.  The basic pattern for calling a message box using this technique is to <code>import ctypes</code> and call <code>windll.user32.MessageBoxA</code>:</p>
<pre class="brush: python;">
from ctypes import *
windll.user32.MessageBoxA(None,&quot;My Message Box&quot;,&quot;Program Name&quot;,0)
</pre>
<p>This simple code produces a message box with the text &#8220;My Message Box&#8221;, an OK button, and &#8220;Program Name&#8221; as the top banner.  When Python encounters <code>windll.user32.MessageBoxA()</code>, program execution pauses until the user clicks the OK button. </p>
<p><img src="http://www.pythonexcels.com/wp-content/uploads/2010/02/20100207_messagebox.png" alt="20100207_messagebox" title="20100207_messagebox" width="132" height="107" class="alignnone size-full wp-image-266" /></p>
<p><strong>Improve Error Checking</strong><br />
Lots of problems can happen when reading user spreadsheet data.  The user can forget to specify an input file.  They could try to have the script read a Word document or other non-spreadsheet file type.  The spreadsheet might be corrupted.  You need to bulletproof your script and guard against potential issues, both known and unknown.  </p>
<p>Previous versions of the script made limited use of the <code>try/except</code> pattern to catch errors. </p>
<pre class="brush: python;">
try:
    wb = excel.Workbooks.Open('ABCDCatering.xls')
except:
    print &quot;Failed to open spreadsheet ABCDCatering.xls&quot;
    sys.exit(1)
</pre>
<p>erppivotdragdrop.py makes more liberal use of <code>try/except</code>, wrapping more of the program code in the <code>try</code> block.  If an error occurs, it can be handled more cleanly with nice warning messages.  The downside of using <code>try/except</code> is that you lose the traceback message telling you where the error occurred.  To get this information back, use the <code>traceback</code> module and the <code>traceback.print_exc()</code> function.  One usage is to call <code>traceback.print_exc()</code> in the <code>except</code> block like this:</p>
<pre class="brush: python;">
import traceback
try:
  a = 1/0
except:
  # Do error recovery
  traceback.print_exc()
</pre>
<p>Now exceptions are caught, handled, and a more detailed traceback is still available. </p>
<p><strong>Running the script</strong><br />
Let&#8217;s test out the script.  First, copy the script to the desktop and drag the ABCDCatering.xls spreadsheet onto the icon.  Python starts running in the command window and begins processing the file you dragged.  If everything ran successfully, you&#8217;ll see a series of messages and the &#8220;Finished&#8221; message box.  </p>
<p><img src="http://www.pythonexcels.com/wp-content/uploads/2010/02/20100207_noerror.png" alt="20100207_noerror" title="20100207_noerror" width="600" height="318" class="alignnone size-full wp-image-267" /></p>
<p>If a problem occurred, a message is displayed in the command window.  At the end of the run, the message box is displayed letting you know that something bad happened and that you should review the error messages.  </p>
<p><img src="http://www.pythonexcels.com/wp-content/uploads/2010/02/20100207_haserror.png" alt="20100207_haserror" title="20100207_haserror" width="600" height="318" class="alignnone size-full wp-image-268" /></p>
<p>Here is the completed script, also available on <a href="http://github.com/pythonexcels/examples">GitHub</a></p>
<pre class="brush: python;">
#
# erppivotdragdrop.py:
# Load raw EPR data, clean up header info,
# insert additional data fields and build 5 pivot tables
# Support drag and drop of multiple spreadsheets
#
import win32com.client as win32
win32c = win32.constants
import sys
import itertools
import re
import traceback
from ctypes import *

tablecount = itertools.count(1)

def addpivot(wb,sourcedata,title,filters=(),columns=(),
             rows=(),sumvalue=(),sortfield=&quot;&quot;):
    &quot;&quot;&quot;Build a pivot table using the provided source location data
    and specified fields
    &quot;&quot;&quot;
    newsheet = wb.Sheets.Add()
    newsheet.Cells(1,1).Value = title
    newsheet.Cells(1,1).Font.Size = 16

    # Build the Pivot Table
    tname = &quot;PivotTable%d&quot;%tablecount.next()

    pc = wb.PivotCaches().Add(SourceType=win32c.xlDatabase,
                                 SourceData=sourcedata)
    pt = pc.CreatePivotTable(TableDestination=&quot;%s!R4C1&quot;%newsheet.Name,
                             TableName=tname,
                             DefaultVersion=win32c.xlPivotTableVersion10)
    wb.Sheets(newsheet.Name).Select()
    wb.Sheets(newsheet.Name).Cells(3,1).Select()
    for fieldlist,fieldc in ((filters,win32c.xlPageField),
                            (columns,win32c.xlColumnField),
                            (rows,win32c.xlRowField)):
        for i,val in enumerate(fieldlist):
            wb.ActiveSheet.PivotTables(tname).PivotFields(val).Orientation = fieldc
            wb.ActiveSheet.PivotTables(tname).PivotFields(val).Position = i+1

    wb.ActiveSheet.PivotTables(tname).AddDataField(
        wb.ActiveSheet.PivotTables(tname).PivotFields(sumvalue[7:]),
        sumvalue,
        win32c.xlSum)
    if len(sortfield) != 0:
        wb.ActiveSheet.PivotTables(tname).PivotFields(sortfield[0]).AutoSort(sortfield[1], sumvalue)
    newsheet.Name = title

    # Uncomment the next command to limit output file size, but make sure
    # to click Refresh Data on the PivotTable toolbar to update the table
    #
    # newsheet.PivotTables(tname).SaveData = False

    return tname

def runexcel(args):
    &quot;&quot;&quot;Open the spreadsheet ABCDCatering.xls, clean it up,
    and add pivot tables
    &quot;&quot;&quot;
    sawerror = False
    print &quot;Running erppivotdragdrop&quot;
    if len(args) == 1:
        windll.user32.MessageBoxA(None,&quot;Error: Please drag at least one Excel file&quot;,&quot;erppivotdragdrop&quot;,0)
        sys.exit(1)
    try:
        excel = win32.gencache.EnsureDispatch('Excel.Application')
        for fname in args[1:]:
            if not re.search(r'\.(?i)xlsx?$',fname):
                print &quot;Error: File %s doesn't seem to be an Excel file, expecting .xls or .xlsx file&quot; % fname
                sawerror = True
                continue
            if not re.match('[A-Za-z]:',fname):
                print &quot;Error: erppivotdragdrop doesn't support command line execution&quot;
                print &quot;       Please drag and drop the Excel file onto the program icon&quot;
                sawerror = True
                continue
            print &quot;Processing %s&quot; % fname
            try:
                wb = excel.Workbooks.Open(fname)
            except:
                print &quot;Failed to open Excel file %s, skipping&quot; % fname
                sawerror = True
                continue

            try:
                ws = wb.Sheets('Sheet1')
            except:
                print &quot;Failed to open Sheet 'Sheet1' in file %s, skipping&quot; % fname
                wb.Close()
                sawerror = True
                continue

            xldata = ws.UsedRange.Value
            newdata = []
            for row in xldata:
                if len(row) == 13 and row[-1] is not None:
                    newdata.append(list(row))
            lasthdr = &quot;Col A&quot;
            for i,field in enumerate(newdata[0]):
                if field is None:
                    newdata[0][i] = lasthdr + &quot; Name&quot;
                else:
                    lasthdr = newdata[0][i]

            logolookup = {'Applied Materials':'AMAT', 'Electronic Arts':'EA',
                          'Hewlett-Packard':'HP', 'KLA-Tencor':'KLA'}
            if (&quot;Company Name&quot; in newdata[0]):
                cindx = newdata[0].index(&quot;Company Name&quot;)
                newdata[0][cindx+1:cindx+1] = [&quot;Logo Name&quot;]
                for rcnt in range(1,len(newdata)):
                    if newdata[rcnt][cindx] in logolookup:
                        newdata[rcnt][cindx+1:cindx+1] = [logolookup[newdata[rcnt][cindx]]]
                    else:
                        newname = newdata[rcnt][cindx].split()[0]
                        newdata[rcnt][cindx+1:cindx+1] = [newname]
                        logolookup[newdata[rcnt][cindx]] = newname

            foodlookup = {'Caesar Salad':'Salad', 'Cheese Pizza':'Pizza',
                          'Cheeseburger':'Burger', 'Chocolate Sundae':'Dessert',
                          'Churro':'Snack', 'Hamburger':'Burger', 'Hot Dog':'HotDog',
                          'Pepperoni Pizza':'Pizza', 'Potato Chips':'Snack',
                          'Soda':'Drink'}
            if (&quot;Food Name&quot; in newdata[0]):
                cindx = newdata[0].index(&quot;Food Name&quot;)
                newdata[0][cindx+1:cindx+1] = [&quot;Food Category&quot;]
                for rcnt in range(1,len(newdata)):
                    if newdata[rcnt][cindx] in foodlookup:
                        newdata[rcnt][cindx+1:cindx+1] = [foodlookup[newdata[rcnt][cindx]]]
                    else:
                        newdata[rcnt][cindx+1:cindx+1] = ['UNDEFINED']

            rowcnt = len(newdata)
            colcnt = len(newdata[0])
            wsnew = wb.Sheets.Add()
            wsnew.Range(wsnew.Cells(1,1),wsnew.Cells(rowcnt,colcnt)).Value = newdata
            wsnew.Columns.AutoFit()

            src = &quot;%s!R1C1:R%dC%d&quot;%(wsnew.Name,rowcnt,colcnt)

            # What were the total sales in each of the last four quarters?
            addpivot(wb,src,
                     title=&quot;Sales by Quarter&quot;,
                     filters=(),
                     columns=(),
                     rows=(&quot;Fiscal Quarter&quot;,),
                     sumvalue=&quot;Sum of Net Booking&quot;,
                     sortfield=())

            # What are the sales for each food item in each quarter?
            addpivot(wb,src,
                     title=&quot;Sales by Food Item&quot;,
                     filters=(),
                     columns=(&quot;Food Name&quot;,),
                     rows=(&quot;Fiscal Quarter&quot;,),
                     sumvalue=&quot;Sum of Net Booking&quot;,
                     sortfield=())

            # Who were the top 10 customers for ABCD Catering in 2009?
            addpivot(wb,src,
                     title=&quot;Top 10 Customers&quot;,
                     filters=(),
                     columns=(),
                     rows=(&quot;Company Name&quot;,),
                     sumvalue=&quot;Sum of Net Booking&quot;,
                     sortfield=(&quot;Company Name&quot;,win32c.xlDescending))

            # Who was the highest producing sales rep for the year?
            addpivot(wb,src,
                     title=&quot;Top Sales Reps&quot;,
                     filters=(),
                     columns=(),
                     rows=(&quot;Sales Rep Name&quot;,&quot;Company Name&quot;),
                     sumvalue=&quot;Sum of Net Booking&quot;,
                     sortfield=(&quot;Sales Rep Name&quot;,win32c.xlDescending))

            # What food item had the highest unit sales in Q4?
            ptname = addpivot(wb,src,
                     title=&quot;Unit Sales by Food&quot;,
                     filters=(&quot;Fiscal Quarter&quot;,),
                     columns=(),
                     rows=(&quot;Food Name&quot;,),
                     sumvalue=&quot;Sum of Quantity&quot;,
                     sortfield=(&quot;Food Name&quot;,win32c.xlDescending))
            wb.Sheets(&quot;Unit Sales by Food&quot;).PivotTables(ptname).PivotFields(&quot;Fiscal Quarter&quot;).CurrentPage = &quot;2009-Q4&quot;

            # What food category had the highest unit sales in Q4?
            ptname = addpivot(wb,src,
                     title=&quot;Unit Sales by Food Category&quot;,
                     filters=(&quot;Fiscal Quarter&quot;,),
                     columns=(),
                     rows=(&quot;Food Category&quot;,),
                     sumvalue=&quot;Sum of Quantity&quot;,
                     sortfield=(&quot;Food Category&quot;,win32c.xlDescending))
            wb.Sheets(&quot;Unit Sales by Food Category&quot;).PivotTables(ptname).PivotFields(&quot;Fiscal Quarter&quot;).CurrentPage = &quot;2009-Q4&quot;

            outfname = re.sub('(?i)\.xlsx?','_new',fname)
            try:
                if int(float(excel.Version)) &gt;= 12:
                    wb.SaveAs(outfname+'.xlsx',win32c.xlOpenXMLWorkbook)
                    print &quot;Wrote %s&quot; % outfname+'.xlsx'
                else:
                    wb.SaveAs(outfname+'.xls')
                    print &quot;Wrote %s&quot; % outfname+'.xls'
            except:
                print &quot;Error: Problem during file save&quot;
                sawerror = True
            wb.Close()
        if sawerror:
            print &quot;Errors occurred, please check the above messages&quot;
            windll.user32.MessageBoxA(None,&quot;Error: Problems occurred, please check them and try again&quot;,&quot;erppivotdragdrop&quot;,0)
        else:
            print &quot;Finished&quot;
            windll.user32.MessageBoxA(None,&quot;Finished&quot;,&quot;erppivotdragdrop&quot;,0)
    except:
        traceback.print_exc()
        print &quot;Errors occurred, please check the above messages&quot;
        windll.user32.MessageBoxA(None,&quot;Error: Problems occurred, please check them and try again&quot;,&quot;erppivotdragdrop&quot;,0)
    excel.Application.Quit()

if __name__ == &quot;__main__&quot;:
    runexcel(sys.argv)
</pre>
<p><strong>Prerequisites</strong><br />
Python (refer to <a href="http://www.python.org">http://www.python.org</a>)</p>
<p>Win32 Python module (refer to <a href="http://sourceforge.net/projects/pywin32">http://sourceforge.net/projects/pywin32</a>)</p>
<p>Microsoft Excel (refer to <a href="http://office.microsoft.com/excel">http://office.microsoft.com/excel</a>)</p>
<p><strong>Source Files and Scripts</strong><br />
Source for the program erppivotextended.py and spreadsheet file ABCDCatering.xls are available at<br /><a href="http://github.com/pythonexcels/examples">http://github.com/pythonexcels/examples</a></p>
<p>Thanks &#8212; Dan</p>
]]></content:encoded>
			<wfw:commentRss>http://www.pythonexcels.com/2010/02/a-user-friendly-experience/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
