ExcelWriter

From Bio.scipy.org

Jump to: navigation, search

CSV (originally "comma separated value") files are often used to export data in a Microsoft Excel compatible format for easy 'manual' access.

CSV files, whether separated with commas, semicolons or tabulators often create problems though, because the data format of the cells is not specified. By default Excel uses the current user's language settings to intepret the data, which by default prevents numbers with a dot as decimal separator from being read correctly on German systems - Germany uses a comma as decimal separator. In addition, Excel has a 'smart' guessing algorithm that has a tendecy to format numbers as dates.

The class below circumvents the problem by creating XML files that carry type information for the cells, in an excel compatible mannner. See its docstring for usage.



#BSD License 
#Copyright Florian Finkernagel, August 2007
#http://bio.scipy.org/wiki/index.php/Cookbook

#All rights reserved. 



#Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 
#Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 
#Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials #provided with the distribution. 
#Neither the name of the bio.scipy.org nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written #permission. 


#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
#SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
#INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
#USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""A simple class (ExcelWriter) to write Excel (2003+) compatible XML files as an improvement or alternative to the
commonly used CSV files, especially if you have trouble with language differences (points vs. commas for
european scientist)"""

import sys
import StringIO

# file meta data

__version__ = "20070919"

__author__ = "Florian Finkernagel"

__license__ = "BSD"

class ExcelCell:
	"""A data holder for all cells"""
	def __init__(self,data,type, tags=""):
		self.Type = type
		self.Data = data
		self.Tags = tags

class ExcelWriter:
	"""Writes Excel-compatible XML files.
	Usage:
		e = ExcelWriter()
		e.addString("Column 1")
		e.addString("Column 2")
		e.finishRow()
		e.addNumber(25)
		e.addNumber(12.23)
		e.finishRow()
		o = open("myFile.xls","wb")
		o.write(e.render())
		o.close()
	"""
	def __init__(self):
		self.Rows = []
		self.CurrentRow = []
		
	def render(self):
		o = """<?xml version="1.0"?>
<ss:Workbook  xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   	<ss:Styles>
		<ss:Style ss:ID="1">
			<Alignment ss:Vertical="Bottom" ss:WrapText="1"/> 
		</ss:Style>
	</ss:Styles>

    <ss:Worksheet ss:Name="Sheet1">
        <ss:Table>"""
        	for row in self.Rows:
        		o += "<ss:Row>"
        		for cell in row:
        			o += """<ss:Cell ss:StyleID="1">
                    <ss:Data ss:Type="%(type)s" %(tags)s>%(data)s</ss:Data>
                </ss:Cell>""" % {"type": cell.Type, "data": cell.Data, "tags": cell.Tags}
        		o += "</ss:Row>"
	        o += """
        </ss:Table>
    </ss:Worksheet>
</ss:Workbook>"""
        
		return o
		
	def addString(self,s):
		self.CurrentRow.append( ExcelCell(s,'String') )
		
	def addNumber(self,i):
		self.CurrentRow.append ( ExcelCell(str(i), "Number") )
		
	def addPValue(self,p):
		"""adds a number formated as 'scientific' with two places after the comma, commonly used for example for p-values"""
		self.CurrentRow.append ( ExcelCell("%(i)2e" % { "i": p }, "Number") )
		
	def addDNASequence(self,sequence):
		"""Adds a colored DNA-sequence (colors similar to Weblogo, http://weblogo.berkeley.edu/)"""
		s = sequence.upper()
		s = s.replace("A","--A--")
		s = s.replace("C","--C--")
		s = s.replace("G","--G--")
		s = s.replace("T","--T--")
		s = s.replace('--A--','<Font html:Color="#25952f">A</Font>')		
		s = s.replace('--C--','<Font html:Color="#203d99">C</Font>')		
		s = s.replace('--G--','<Font html:Color="#ffc900">G</Font>')		
		s = s.replace('--T--','<Font html:Color="#d61408">T</Font>')		
		self.CurrentRow.append( ExcelCell('<B>' + s + '</B>',"String", 'xmlns="http://www.w3.org/TR/REC-html40"') )
			
	def finishRow(self):
		self.Rows.append(self.CurrentRow)
		self.CurrentRow = []
Personal tools