当前位置: 首页>>代码示例>>Python>>正文


Python Workbook.close方法代码示例

本文整理汇总了Python中xlsxwriter.Workbook.close方法的典型用法代码示例。如果您正苦于以下问题:Python Workbook.close方法的具体用法?Python Workbook.close怎么用?Python Workbook.close使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在xlsxwriter.Workbook的用法示例。


在下文中一共展示了Workbook.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: write_cell_errors

# 需要导入模块: from xlsxwriter import Workbook [as 别名]
# 或者: from xlsxwriter.Workbook import close [as 别名]
def write_cell_errors(xlsxname, header, lines, cells_to_mark):
    workbook  = Workbook(join(SPREADSHEETS_DIR, xlsxname))
    cell_fmt  = workbook.add_format()
    cell_fmt.set_bg_color('cyan')
    worksheet = workbook.add_worksheet()
    write_sheet(worksheet, cell_fmt, header, lines, cells_to_mark)
    workbook.close()
开发者ID:baharev,项目名称:CSV_Test,代码行数:9,代码来源:csv_test.py

示例2: exportExcelDirect

# 需要导入模块: from xlsxwriter import Workbook [as 别名]
# 或者: from xlsxwriter.Workbook import close [as 别名]
def exportExcelDirect(request, adict):
    try:
        l_parm = adict['ex_parm']
        l_parm['title']  # : '文档标题', 第一行各列合并居中写入title
        l_parm['cols']   # :['列名1','列名2','列名3'], //列标题
        l_parm['rows']   # :[      ['行1列1','行1列2','行1列3'],       #         ['行2列1','行2列2','行2列3'],
        import io
        from xlsxwriter import Workbook
        output = io.BytesIO()
        workbook = Workbook(output)
        worksheet = workbook.add_worksheet('export')
        worksheet.write('A1',l_parm['title'])
        # Text with formatting.              ..........  write( row, cols, content )
        for i in range(len(l_parm['cols'])):
            worksheet.write(1, i, l_parm['cols'][i])
        for i in range(len(l_parm['rows'] )):
            for j in range(len(l_parm['rows'][i])):
                worksheet.write(i + 2, j, l_parm['rows'][i][j])
        workbook.close()
        output.seek(0)
        response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    except Exception as e:
        ls_err = str(e.args)
        response = HttpResponse(str("导出excel失败:" + ls_err), content_type="application/text")

    response['Content-Disposition'] = "attachment; filename=test.xlsx"
    return response
开发者ID:derris,项目名称:djFrame,代码行数:29,代码来源:ajaxRespBase.py

示例3: dump_info_xlsx

# 需要导入模块: from xlsxwriter import Workbook [as 别名]
# 或者: from xlsxwriter.Workbook import close [as 别名]
def dump_info_xlsx():
    from xlsxwriter import Workbook
    
    wb = Workbook(configuration['outputfile'] + '.xlsx')
    ws = wb.add_worksheet("CollatedInfo")
    
    ordered_list = 'Name,Matric,Team,MainLineCount,MainWordCount,TestLineCount,TestWordCount,DocsLineCount,DocsWordCount,MainFile,TestFile,DocsFile'.split(",")
    
    row = 0
    for header in ordered_list:
        col = ordered_list.index(header)
        ws.write(row, col, header)
        
    row = 1
    
    for matric in sorted(studentlist.keys()):
        for k , v in studentlist[matric].items():
            if k == 'MainFile':
                pass
            elif k == 'Main':
                pass
            elif k == 'TestFile':
                pass
            elif k == 'Test':
                pass
            col = ordered_list.index(k)
            ws.write(row, col, v)
        row += 1
        
    wb.close()
开发者ID:okkhoy,项目名称:pyscripts,代码行数:32,代码来源:movefiles.py

示例4: action

# 需要导入模块: from xlsxwriter import Workbook [as 别名]
# 或者: from xlsxwriter.Workbook import close [as 别名]
def action(args):

    book = Workbook()
    filetype = args.type
    (infiles, ) = args.infiles
    if filetype == 'Analysis':
        tabs = ['0_QC', '1_QC_Metrics', '2_QC_by_Gene', '3_QC_by_Exon',
                '4_SV_Gridss', '5_SV_Breakdancer', '6_SV_Pindel',
                '7_CNV_Gene', '8_CNV_Exon', '9_Clinically_Flagged', 
                '10_SNP','11_INDEL', '12_MSI', '13_Amplicons', '14_PolyHunter']
        #    for each tab, find its file and process.
        for tab in tabs:
            try:
                #Find file in infiles
                sheet_name, fname = process_files(infiles, tab, filetype)
                print sheet_name, fname
                write_workbook(sheet_name, book, fname)
            except TypeError:
                print "Tab %s not processed" % tab
    elif filetype == 'Combined':
        for fname in infiles:
            (f_path, f_name) = os.path.split(fname)
            if re.search(str(filetype), f_name):
                (f_short_name, f_extension) = os.path.splitext(f_name)
                sheet_name = f_short_name.split('Combined_')
                sheet_name = '_'.join(sheet_name[1:30])
                print sheet_name, fname
                write_workbook(sheet_name, book, fname)
    book.filename=args.outfile

    book.close()
开发者ID:sheenams,项目名称:munge,代码行数:33,代码来源:xlsxmaker.py

示例5: verified

# 需要导入模块: from xlsxwriter import Workbook [as 别名]
# 或者: from xlsxwriter.Workbook import close [as 别名]
def verified(context, collaborator, test, outpath=None):
    """Export variants which have been verified for an institute
        and write them to an excel file.

    Args:
        collaborator(str): institute id
        test(bool): True if the function is called for testing purposes
        outpath(str): path to output file

    Returns:
        written_files(int): number of written or simulated files
    """
    written_files = 0
    collaborator = collaborator or 'cust000'
    LOG.info('Exporting verified variants for cust {}'.format(collaborator))

    adapter = context.obj['adapter']
    verified_vars = adapter.verified(institute_id=collaborator)
    LOG.info('FOUND {} verified variants for institute {}'.format(len(verified_vars), collaborator))


    if not verified_vars:
        LOG.warning('There are no verified variants for institute {} in database!'.format(collaborator))
        return None

    document_lines = export_verified_variants(verified_vars)

    today = datetime.datetime.now().strftime('%Y-%m-%d')
    document_name = '.'.join(['verified_variants', collaborator, today]) + '.xlsx'

    # If this was a test and lines are created return success
    if test and document_lines:
        written_files +=1
        LOG.info('Success. Verified variants file contains {} lines'.format(len(document_lines)))
        return written_files

    # create workbook and new sheet
    # set up outfolder
    if not outpath:
        outpath = str(os.getcwd())
    workbook = Workbook(os.path.join(outpath,document_name))
    Report_Sheet = workbook.add_worksheet()

    # Write the column header
    row = 0
    for col,field in enumerate(VERIFIED_VARIANTS_HEADER):
        Report_Sheet.write(row,col,field)

    # Write variant lines, after header (start at line 1)
    for row, line in enumerate(document_lines,1): # each line becomes a row in the document
        for col, field in enumerate(line): # each field in line becomes a cell
            Report_Sheet.write(row,col,field)
    workbook.close()

    if os.path.exists(os.path.join(outpath,document_name)):
        LOG.info('Success. Verified variants file of {} lines was written to disk'. format(len(document_lines)))
        written_files += 1

    return written_files
开发者ID:Clinical-Genomics,项目名称:scout,代码行数:61,代码来源:variant.py

示例6: write_mismatch

# 需要导入模块: from xlsxwriter import Workbook [as 别名]
# 或者: from xlsxwriter.Workbook import close [as 别名]
def write_mismatch(filename, etalon, tocomp, mismatch):
    workbook  = Workbook(join(SPREADSHEETS_DIR, get_filebase(filename)+'.xlsx'))
    cell_fmt  = workbook.add_format()
    cell_fmt.set_bg_color('cyan')
    worksheet = workbook.add_worksheet(name='test')
    write_sheet(worksheet, cell_fmt, *tocomp, cells_to_mark=mismatch)
    worksheet = workbook.add_worksheet(name='etalon')
    write_sheet(worksheet, cell_fmt, *etalon)
    workbook.close()
开发者ID:baharev,项目名称:CSV_Test,代码行数:11,代码来源:csv_test.py

示例7: write_presentation

# 需要导入模块: from xlsxwriter import Workbook [as 别名]
# 或者: from xlsxwriter.Workbook import close [as 别名]
 def write_presentation(self, values, records, output):
     workbook = Workbook(output, {'constant_memory': True})
     worksheet = workbook.add_worksheet()
     for column, value in enumerate(values):
         worksheet.write_string(0, column, value)
     for row, record in enumerate(records):
         value_iterator = enumerate([unicode(record[v]) for v in values])
         for column, text in value_iterator:
             worksheet.write_string(row + 1, column, text)
     workbook.close()
开发者ID:DirectEmployers,项目名称:MyJobs,代码行数:12,代码来源:xlsx.py

示例8: dispatch

# 需要导入模块: from xlsxwriter import Workbook [as 别名]
# 或者: from xlsxwriter.Workbook import close [as 别名]
def dispatch(dataset):
    buf = StringIO()
    wb = Workbook(buf,
                  {'constant_memory': True,
                   'in_memory': True,
                   'default_date_format': 'yyyy/mm/dd hh:mm:ss'}
                 )
    format_ = wb.add_format(FORMAT)

    # dataset metadata
    ws = wb.add_worksheet('Global attributes')
    write_metadata(ws, dataset, 0, 0, format_)

    # 1D grids
    for grid in [g for g in walk(dataset, GridType) if len(g.shape) == 1]:
        logger.debug('Grid {}'.format(grid.name))
        ws = wb.add_worksheet(grid.name)

        # headers
        ws.write(0, 0, grid.dimensions[0], format_)
        ws.write(0, 1, grid.name, format_)

        # data
        for j, data in enumerate(grid.data):
            for i, value in enumerate(numpy.asarray(data)):
                ws.write(i+1, 1-j, value)

        # add var metadata
        write_metadata(ws, grid, 0, 2, format_)

    # sequences
    for seq in walk(dataset, SequenceType):
        logger.debug('Sequence {}'.format(seq.name))

        ws = wb.add_worksheet(seq.name)

        # add header across the first row
        for j, var_ in enumerate(seq.keys()):
            ws.write(0, j, var_, format_)

        # add data in the subsequent rows
        for i, row in enumerate(seq.data):
            for j, value in enumerate(row):
                ws.write(i+1, j, value)

        # add var metadata in columns to the right of the data
        n = 0
        j = len(seq.keys())+1
        for child in seq.children():
            logger.debug("Child {}".format(child.name))
            ws.merge_range(n, j, n, j+1, child.name, format_)
            n = write_metadata(ws, child, n+1, j, format_)+1

    wb.close()
    return buf
开发者ID:pacificclimate,项目名称:pydap.responses.xlsx,代码行数:57,代码来源:__init__.py

示例9: _open_worksheet

# 需要导入模块: from xlsxwriter import Workbook [as 别名]
# 或者: from xlsxwriter.Workbook import close [as 别名]
 def _open_worksheet(xlsx_file):
     """
     Enable XlsxWriter Worksheet object to be opened, operated on, and
     then automatically closed within a `with` statement. A filename or
     stream object (such as a ``BytesIO`` instance) is expected as
     *xlsx_file*.
     """
     workbook = Workbook(xlsx_file, {"in_memory": True})
     worksheet = workbook.add_worksheet()
     yield workbook, worksheet
     workbook.close()
开发者ID:biggihs,项目名称:python-pptx,代码行数:13,代码来源:xlsx.py

示例10: genera_e_salva

# 需要导入模块: from xlsxwriter import Workbook [as 别名]
# 或者: from xlsxwriter.Workbook import close [as 别名]
    def genera_e_salva(self, nome='File.xlsx', scadenza=None, ordina_fogli=True, save_to_memory=False):
        """
        Genera il file e lo salva su database.
        :param nome: Il nome del file da allegare (opzionale, default 'File.xlsx').
        :param scadenza: Scadenza del file. Domani.
        :return:
        """

        generatore = GeneratoreNomeFile('allegati/')
        zname = generatore(self, nome)

        self.prepara_cartelle(MEDIA_ROOT + zname)

        if save_to_memory:
            workbook = Workbook(self.output)
        else:
            workbook = Workbook(MEDIA_ROOT + zname)

        bold = workbook.add_format({'bold': True})

        # Per ogni foglio
        for foglio in [x for x in self.fogli]:

            # Aggiunge il foglio
            worksheet = workbook.add_worksheet(foglio.nome)

            # Aggiunge l'intestazione
            for col, testo in enumerate(foglio.intestazione):
                worksheet.write(0, col, str(testo), bold)

            # Aggiunge il contenuto
            for riga, colonne in enumerate(foglio.contenuto):
                riga += 1  # Indice shiftato per intestazione
                for colonna, testo in enumerate(colonne):
                    if isinstance(testo, datetime):
                        testo = testo.strftime("%d/%m/%Y %H:%M")
                    if isinstance(testo, date):
                        testo = testo.strftime("%d/%m/%Y")
                    if testo == ", ":  # Rimuove campi ', '
                        testo = ""
                    worksheet.write(riga, colonna, str(testo))

        if ordina_fogli:
            workbook.worksheets_objs.sort(key=lambda x: x.name)

        workbook.close()

        if save_to_memory:
            self.output.seek(0)
        else:
            self.file = zname
            self.nome = nome
            self.scadenza = scadenza or domani()
            self.save()
开发者ID:vittoriodargenio,项目名称:jorvik,代码行数:56,代码来源:files.py

示例11: mt_excel_files

# 需要导入模块: from xlsxwriter import Workbook [as 别名]
# 或者: from xlsxwriter.Workbook import close [as 别名]
def mt_excel_files(store, case_obj, temp_excel_dir):
    """Collect MT variants and format line of a MT variant report
    to be exported in excel format

    Args:
        store(adapter.MongoAdapter)
        case_obj(models.Case)
        temp_excel_dir(os.Path): folder where the temp excel files are written to

    Returns:
        written_files(int): the number of files written to temp_excel_dir

    """
    today = datetime.datetime.now().strftime('%Y-%m-%d')
    samples = case_obj.get('individuals')

    query = {'chrom':'MT'}
    mt_variants = list(store.variants(case_id=case_obj['_id'], query=query, nr_of_variants= -1, sort_key='position'))

    written_files = 0
    for sample in samples:
        sample_id = sample['individual_id']
        sample_lines = export_mt_variants(variants=mt_variants, sample_id=sample_id)

        # set up document name
        document_name = '.'.join([case_obj['display_name'], sample_id, today]) + '.xlsx'
        workbook = Workbook(os.path.join(temp_excel_dir,document_name))
        Report_Sheet = workbook.add_worksheet()

        # Write the column header
        row = 0
        for col,field in enumerate(MT_EXPORT_HEADER):
            Report_Sheet.write(row,col,field)

        # Write variant lines, after header (start at line 1)
        for row, line in enumerate(sample_lines,1): # each line becomes a row in the document
            for col, field in enumerate(line): # each field in line becomes a cell
                Report_Sheet.write(row,col,field)
        workbook.close()

        if os.path.exists(os.path.join(temp_excel_dir,document_name)):
            written_files += 1

    return written_files
开发者ID:Clinical-Genomics,项目名称:scout,代码行数:46,代码来源:controllers.py

示例12: get_query_result_excel

# 需要导入模块: from xlsxwriter import Workbook [as 别名]
# 或者: from xlsxwriter.Workbook import close [as 别名]
	def get_query_result_excel(self, sql, excelFile, header='True'):
		'''
			Build an excel file from result set of the sql command \n
			Example: get query result excel		select * from customer		test.xlsx
		'''
		
		cur = self._dbconnection.cursor()
		cur.execute(sql + ';')
		rows = cur.fetchall()
		print(cur.description)
		
		workbook = Workbook(excelFile)
		sheet = workbook.add_worksheet()
		format = workbook.add_format({'bold': True})
		
		if header.lower() == 'true':
			for i, val in enumerate([column[0] for column in cur.description]): sheet.write(0, i, self._f(val), format)	#Write header column
		for r, row in enumerate(rows):
			for c, s in enumerate(row): sheet.write(r+1, c, self._f(s)) # Write table data
		workbook.close()
开发者ID:maddyvn,项目名称:Robot-framework_Test,代码行数:22,代码来源:DBLibrary.py

示例13: generar_layout

# 需要导入模块: from xlsxwriter import Workbook [as 别名]
# 或者: from xlsxwriter.Workbook import close [as 别名]
def generar_layout(datos, salida):
    wb = Workbook(salida)
    ws = wb.add_worksheet('Layout')
    encabezados = '''
Nombre
Inicio
Longitud
Tipo de dato capturado
    '''.split('\n')[1:-1]

    # Escribir encabezados
    col_enc_bg = "#{:02x}{:02x}{:02x}".format(15, 36, 62).upper()
    col_ren2 = "#{:02x}{:02x}{:02x}".format(220, 230, 241).upper()
    format_enc = wb.add_format({'bold': True, 'font_color': 'white', 'bg_color': col_enc_bg})
    format_ren1 = wb.add_format({'border': 1})
    format_ren2 = wb.add_format({'border': 1, 'bg_color': col_ren2})
    for col, encabezado in enumerate(encabezados):
        ws.write(0, col, encabezado, format_enc)

    # Escribir datos del diccionario    
    for renglon, registro in enumerate(datos, 1):
        formato = format_ren1 if renglon % 2 == 0 else format_ren2
        # Registros2 = namedtuple('Registros', 'etiqueta nombre inicio longitud tipo_cap')
        ws.write(renglon, 0, registro.etiqueta, formato)
        ws.write(renglon, 1, int(registro.inicio), formato)
        ws.write(renglon, 2, int(registro.longitud), formato)
        ws.write(renglon, 3, registro.tipo_cap, formato)


    # Aplicando formato a la hoja
    ws.freeze_panes(1, 0)
    ws.autofilter('A1:D1')
    ws.set_column(0, 0, 55)
    ws.set_column(1, 1, 8)
    ws.set_column(2, 2, 10)
    ws.set_column(3, 3, 25)
    ws.hide_gridlines(2)
    wb.close()
    click.launch(salida)

    print("Layout generado")
开发者ID:EvasTripi,项目名称:gen_layout,代码行数:43,代码来源:gen_layout.py

示例14: medicamentos_topOrganizacionesPorPedidoExcel

# 需要导入模块: from xlsxwriter import Workbook [as 别名]
# 或者: from xlsxwriter.Workbook import close [as 别名]
def medicamentos_topOrganizacionesPorPedidoExcel(request):
    datos = request.session['estadistica']['excel']['datos']
    medicamento = request.session['estadistica']['excel']['medicamento']
    excel = io.BytesIO()
    workbook = Workbook(excel, {'in_memory': True})
    worksheet = workbook.add_worksheet()
    titulo = workbook.add_format({
        'font_name':'Arial',
        'font_size': 12,
        'font_color': 'navy',
        'bold': True
    })
    encabezado = workbook.add_format({
        'font_name': 'Arial',
        'bold': True
    })
    alignLeft = workbook.add_format({
        'align': 'left',
    })
    worksheet.write('A1:B1', 'Organizaciones mas demandantes del medicamento '+medicamento+' (por pedido)', titulo)

    worksheet.set_column('B:B', 40)
    worksheet.set_column('C:C', 20)
    worksheet.write('A2', '#', encabezado)
    worksheet.write('B2', 'Organizacion', encabezado)
    worksheet.write('C2', 'Cantidad', encabezado)
    fila = 2
    tope = len(datos)
    for i in range(0, tope):
        worksheet.write(fila, 0, i + 1, alignLeft)
        worksheet.write(fila, 1, datos[i]['organizacion'], alignLeft)
        worksheet.write(fila, 2, datos[i]['cantidad'], alignLeft)
        fila += 1
    workbook.close()

    excel.seek(0)

    response = HttpResponse(excel.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    response['Content-Disposition'] = "attachment; filename=OrganizacionesMasDemandantesDeMedicamentoPorPedido.xlsx"
    return response
开发者ID:silvertw,项目名称:farma,代码行数:42,代码来源:views.py

示例15: write_excel

# 需要导入模块: from xlsxwriter import Workbook [as 别名]
# 或者: from xlsxwriter.Workbook import close [as 别名]
def write_excel(date, name, names=None, shift=1, id_col=0, chart_cell='D1', val_col=1):
    workbook = Workbook(name)
    sheet_name = 'TextTiling'
    worksheet = workbook.add_worksheet(sheet_name)
    i = 0
    for value in date:
        if names == None:
            value_name = "%d - %d" % (i + shift, i + shift + 1)
        else:
            value_name = names[i]
        worksheet.write(i, id_col, value_name)
        worksheet.write(i, val_col, value)
        i += 1
    chart = workbook.add_chart({ 'type': 'column'})
    chart.add_series({
        'name': 'Cosines',
        'categories': [sheet_name, 0, id_col, i - 1, id_col],
        'values': [sheet_name, 0, val_col, i - 1, val_col],
    })
    chart.set_size({'width': 920, 'height': 776})
    worksheet.insert_chart(chart_cell, chart)
    workbook.close()
开发者ID:khovansky-al,项目名称:texttiling_ifmo,代码行数:24,代码来源:texttiling.py


注:本文中的xlsxwriter.Workbook.close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。