def generaExcel(xml_files,output_path): excel=ExcelFile() traduccion=creaHojaDeTraduccion(excel) audio = creaHojaDeAudios(excel, "audios") titulos=["nivel","isText","numHijos","texto","atributos","posicion","nombre","nombrePadre"] estructura=creaHojaDeEstructura(excel, titulos) hoja_excel_mapeada=HojaEstructura(estructura) estilo=estiloCeldasSeparadas() fila=1 for file in xml_files: if len(hoja_excel_mapeada.archivosMapeados)>0: last=hoja_excel_mapeada.getArchivosMapeados()[-1]["mapped_in_excel"].end_row fila=last+1 #estructura.write_merge(0,0,0,5,'Merged',estilo) else: fila=1 mapeaXMLenXLS(excel,file, hoja_excel_mapeada, fila) #mapeaXMLenXLS(excel,"../files/xml_files/curso2.xml", hoja_excel_mapeada) hoja_excel_mapeada.hoja.protect = True hoja_excel_mapeada.hoja.hide=True excel.save_xls(output_path) '''
def creaExcel(self): self.excelTraductor = ExcelFile()
class CreadorExcelTraduccion(object): ''' Clase complementaria que nos sirve para crear el archivo xls a partir de los archivos xml. Lee los archivos xml y los transforma en la estructura mapeable Escribe en una hoja excel los xml transformados y define la estructura para que sea posible la operación inversa que realiza CreadorXMLTraducidos ''' def __init__(self): self.excelTraductor=None self.xmls_en_Excel=[] self.hojas={} self.celdas_texto=[] self.celdas_audio=[] def creaExcel(self): self.excelTraductor = ExcelFile() def creaEstructuraDeExcel(self) : ''' Este método crea las hojas necesarias para la aplicación de traducción. Esas hojas son: - Hoja de textos: texts_sheet - Hoja de audios: audios_sheet - Hoja de estructura: structure ''' self.hojas["texts_sheet"]=self.__creaHojaDeTraduccion(self.excelTraductor, "texts_sheet") self.hojas["audios_sheet"]=self.__creaHojaDeAudios(self.excelTraductor, "audios_sheet") self.hojas["structure"]=self.__creaHojaDeEstructura(self.excelTraductor, "structure") def serializaXMLenHoja(self,xml_path, ini_row, ini_col): ''' Params: xml_path: ruta ini_row: fila en que comienza el mapeo ini_col: columna en que comienza el mapeo Este método recibe un archivo xml y dispara el proceso de mapeo de xml en xls usando el objeto serializador: xml_xls_serializer.SerializeXMLinXLS Una vez mapeado, escribe la estructura en las hojas excel correspondientes. ''' nombre_archivo=os.path.basename(xml_path) #Escribimos el título del xml self.excelTraductor.escribeCombinadas(nombre_archivo, row1=ini_row, row2=ini_row, col1=ini_col, col2=8, sheet=self.hojas["structure"]) #Serializamos el xml en el xls con el objeto correspondiente #serializer = xml_xls_serializer.SerializeXMLinXLS(xml_path,self.excelTraductor) serializer = ObjetosTraduccion.SerializaTraduccion(xml_path,self.excelTraductor) serializer.serialize(row=ini_row+1, col=ini_col,hoja=self.hojas["structure"]) #Hoja serializada es un objeto xml_xls_serializer.XMLSerializerInXLS hoja_serializada=serializer.xmlSerializadoEnExcel #Creamos un objeto que describe la estructura mapeada xml_en_excel=XMLenFilasDeExcel(xml_path, hoja_serializada.init_row, hoja_serializada.end_row,hoja_serializada.nodes_mapped_as_row) self.xmls_en_Excel.append(xml_en_excel) return xml_en_excel def __fillAudiosTab(self): tagsaudio = self.getTagsAudioByFile() ini_row=1 #style.alignment.wrap = 1 for audios_file in tagsaudio: nombre_archivo=os.path.basename(audios_file["file"]) self.excelTraductor.escribeCombinadas(nombre_archivo, row1=ini_row, row2=ini_row, col1=0, col2=2, sheet=self.hojas["audios_sheet"]) ini_row+=1 for audios in audios_file["audios"]: try: self.hojas["audios_sheet"].write(ini_row,0,audios.getText()) ini_row+=1 except Exception as ex: print ini_row,ex, "__fillAudiosTab line 128" def fillAudiosTab(self, not_audios=[]): ''' Rellenamos la hoja de textos y añadimos la fórmula a la celda de traducción La celda de traducción remite a la celda 8 o I (translated_text) de la hoja structure ''' print "we fill" xml_mapeados=self.xmls_en_Excel ini_row=1 style_ = ESTILOS.txt_style style_.alignment.wrap = 1 Formula=xlwt.Formula celda_traduccion=8 for mapper in xml_mapeados: nombre_archivo=os.path.basename(mapper.nombre) if nombre_archivo in not_audios: print nombre_archivo+ " is not supposed to be in the audios tab" continue try: self.excelTraductor.escribeCombinadas(nombre_archivo, row1=ini_row, row2=ini_row, col1=0, col2=2, sheet=self.hojas["audios_sheet"]) except: print ini_row,nombre_archivo, "TraductorXmlXls/fillAudiosTab line 232" ini_row+=1 for mapa in mapper.filas_mapeadas: try: txt=mapa.getTag() if mapa.getText() is not None: if txt.upper() == "AUDIO": celda=mapa.getProperty("texto") self.hojas["audios_sheet"].write(ini_row,1,mapa.getText()) #transformamos los índices númericos a indices de excel celdat = xlwt.Utils.rowcol_to_cell(celda['row'],8,True,True) celdat = "\'structure\'!"+celdat self.hojas["audios_sheet"].write(ini_row,2, Formula(celdat)) #print Formula(celdat), celda["texto"]==map.getText(), celda["texto"] ini_row+=1 else: if mapa.getTag()==PAGE_TAG and PAGE_TAG !="": if (PAGINADO): stilo = ESTILOS.bold_style num=mapa.getProperty("atributos")["atributos"] numpag=num["num"] rows=self.__insertDataInRow(numpag, ini_row, ini_row, 0, 0, hoja=self.hojas["audios_sheet"]) except Exception as ex: ini_row+=1 print "->",ini_row, mapa.getText(),ex, "TraductorXmlXls/fillAudiosTab line 259" def fillTranslationTab(self): ''' Rellenamos la hoja de textos y añadimos la fórmula a la celda de traducción La celda de traducción remite a la celda 8 o I (translated_text) de la hoja structure ''' no_prot_style = ESTILOS.not_protected_style xml_mapeados=self.xmls_en_Excel ini_row=1 style = ESTILOS.txt_style #style.alignment.wrap = 1 Formula=xlwt.Formula celda_traduccion=8 for mapper in xml_mapeados: nombre_archivo=os.path.basename(mapper.nombre) self.excelTraductor.escribeCombinadas(nombre_archivo, row1=ini_row, row2=ini_row, col1=0, col2=2, sheet=self.hojas["texts_sheet"]) ini_row+=1 for map in mapper.filas_mapeadas: #if True: try: if map.getText() is not None: celda=map.getProperty("texto") self.hojas["texts_sheet"].write(ini_row,0,map.getText(),style) self.hojas["texts_sheet"].write(ini_row,1,"", no_prot_style) self.hojas["texts_sheet"].write(ini_row,2,map.getTag(),style) #transformamos los índices númericos a indices de excel celdat= xlwt.Utils.rowcol_to_cell(ini_row,1,True,True) celdat="\'texts_sheet\'!"+celdat self.hojas["structure"].write(celda["row"],celda_traduccion, Formula(celdat)) #print Formula(celdat), celda["texto"]==map.getText(), celda["texto"] ini_row+=1 else: if map.getTag()==PAGE_TAG and PAGE_TAG !="": if (PAGINADO): stilo = ESTILOS.titulo_pagina_style num=map.getProperty("atributos")["atributos"] numpag=map.getTag()+": "+num["num"] rows=self.__insertDataInRow(numpag, ini_row, ini_row, 0, 0, hoja=self.hojas["texts_sheet"], estilo=stilo) ini_row=rows[0] except Exception as ex: #celda=map.getProperty("texto") print ini_row,ex, "TraductorXmlXls line 193" def getTagsAudioByFile(self): xml_mapeados=self.xmls_en_Excel audios_by_file=[] for mapper in xml_mapeados: audio_by_file={"file":mapper.nombre, "audios":mapper.getTagsByName("audio")} audios_by_file.append(audio_by_file) return audios_by_file def guardaExcel(self, path): try: self.excelTraductor.save(path) except IOError as ex: raise ExcelError("there is a problem creating the file. ", ex) #print "no se ha podido crear el archivo" ''' METODOS PRIVADOS... : ''' def __creaHojaDeTraduccion(self,excel, nombreHoja="traduccion",amplitud1=75*256,amplitud2=75*256,amplitud3=10*256): hoja=excel.creaHoja(nombreHoja) style = ESTILOS.titulo_columna_style hoja.col(0).width=amplitud1 hoja.col(1).width=amplitud2 hoja.col(2).width=amplitud3 hoja.write(0,0,"Original text", style) hoja.write(0,1,"Translation", style) hoja.write(0,2,"Tag name", style) hoja.protect = True hoja.password="******" return hoja def __creaHojaDeAudios(self,excel, nombreHoja="traduccion"): hoja=excel.creaHoja(nombreHoja) hoja.col(1).width=80*256 hoja.col(2).width=80*256 style=ESTILOS.titulo_columna_style hoja.write(0,1,"Audio", style) hoja.write(0,2,"Translation", style) if PAGINADO: hoja.write(0,0,"Screen", style) hoja.protect = True hoja.password="******" return hoja def __creaHojaDeEstructura(self,excel, nombreHoja="traduccion", titulos=["level","isText","numChilds","text","attributes","position","tag_name","parent_name", "translated_text"]): hoja=excel.creaHoja(nombreHoja) excel.listToRow(titulos,sheet=hoja) hoja.protect = True hoja.password="******" return hoja def __insertDataInRow(self,data, ini_row1, ini_row2, ini_col1, ini_col2, hoja=None, estilo=None): '''Podemos sobreescribir este método para conseguir filas añadidas en medio" return una tupla con las posiciones cambiadas ''' if estilo is None: estilo = ESTILOS.titulo_pagina_style self.excelTraductor.escribeCombinadas(data, row1=ini_row1, row2=ini_row2, col1=ini_col1, col2=ini_col2, sheet=hoja, style=estilo) ini_row1+=1 return (ini_row1, ini_row2, ini_col1, ini_col2) def __escribeTitulo(self, ini_cell,end_cell, data): pass def __escribeCelda(self,ini_cell,end_cell, data): pass
Created on 21/09/2011 @author: scalvofe ''' import os ''' import xml_xls_serializer.xml_maps.xml_node_mappers from xml_xls_serializer.xml_xls_extracter.xml_extract_tag import TagExtracter from xml_xls_serializer.xml_xls_extracter.xls_xml_mapper import ExcelMapper, MapperToXML from xls_utils.xls import ExcelFile MappedError=xml_xls_serializer.xml_maps.xml_node_mappers.MappedError XlsMap=xml_xls_serializer.xml_maps.xml_node_mappers.MapperXMLinXls from xlwt import XFStyle, Borders, Pattern, Font ''' from xml_xls_serializer.xml_xls_serializer import SerializeXMLinXLS from xls_utils.xls import ExcelFile def getFiles(fileType,path): list_of_files = [os.path.join(path,file) for file in os.listdir(path) if file.lower().endswith(fileType)] return list_of_files if __name__=="__main__": path="../files/xml_files/" files=getFiles("xml",path) excel=ExcelFile() serializer= SerializeXMLinXLS(files[0],excel) titulos=["nivel","isText","numHijos","texto","atributos","posicion","nombre","nombrePadre"] serializer.serialize(sheetName="hoja_estructura") excel.save("hoja_de_prueba.xls") serializado=serializer.getXMLSerializedAsXLS() #xml serializado en excel serializer.deserialize(wb_path="hoja_de_prueba.xls", output_file="salida_.xml", sheet_name="hoja_estructura", ini_row=0, end_row=125)