[docs]classXlsxWriter(BaseWriter):""" Writer class with output to XLSX files. For each table, a corresponding sheet in an Excel workbook will be created. """name="xlsx"def__init__(self,workdir,tables,options,schema,filename="result.xlsx"):""" :param workdir: Working directory :param tables: The table objects :param options: Flattening options """super().__init__(workdir,tables,options,schema=schema)self.col_index=collections.defaultdict(dict)self.path=workdir/filenameself.workbook=xlsxwriter.Workbook(self.path,{"constant_memory":True})self.row_counters={}def__enter__(self):""" Write the headers to the output file. """forname,tableinself.tables.items():table_name,headers=self.init_sheet(name,table)sheet=self.workbook.add_worksheet(table_name)forcol_index,col_nameinenumerate(headers):self.col_index[name][col_name]=col_indextry:sheet.write(0,col_index,headers[col_name])exceptXlsxWriterExceptionaserr:LOGGER.error(# noqa: TRY400 # UX_("Failed to write header {} to xlsx sheet {} with error {}").format(col_name,name,err))self.row_counters[name]=1returnselfdef__exit__(self,*args):""" Close the workbook. """LOGGER.info(_("Dumped all sheets to file to file '{}'").format(self.path))self.workbook.close()
[docs]defwriterow(self,table,row):""" Write a row to the output file. """table_name=self.names.get(table,table)sheet=self.workbook.get_worksheet_by_name(table_name)columns=self.col_index[table]ifnotcolumns:LOGGER.error(_("Invalid table {}").format(table))returnforcolumn,valueinrow.items():ifisinstance(value,bool):value=str(value)try:col_index=columns[column]exceptKeyError:LOGGER.error(# noqa: TRY400 # UX_("Operation produced invalid path. This a software bug, please send issue to developers"))LOGGER.error(# noqa: TRY400 # UX_("Failed to write column {} to xlsx sheet {}").format(column,table))returntry:sheet.write(self.row_counters[table],col_index,value)exceptXlsxWriterExceptionaserr:LOGGER.error(# noqa: TRY400 # UX_("Failed to write column {} to xlsx sheet {} with error {}").format(column,table,err))self.row_counters[table]+=1