export as excel
    filename: file name
    titles: title for this table
    qs: queryset to export
    func_data: a function to format object to list. ex: `lambda o: [o.pk, o.name]`
764714
def simple_export2xlsx(filename, titles, qs, func_data):
    
    output = BytesIO()
    wb = xlwt.Workbook(output)
    ws = wb.add_worksheet(filename)
    header_fmt = wb.add_format()
    header_fmt.set_bg_color('#C4D89E')
    row_idx = 0
    row_idx = xlsw_write_row(ws, row_idx, titles, header_fmt)
    for o in qs:
        row_idx = xlsw_write_row(ws, row_idx, func_data(o))
    fn = '%s-%s.xlsx' % (filename, datetime.now())
    return export_xlsx(wb, output, fn)
1243383
def save fname, options={}
      File.open(fname,"wb"){ |f| f << export(options) }
    end
262202
def save_as(self):
        """"""
        filename = splitext(self.filename)[0]
        filename, _ = QFileDialog.getSaveFileName(self, 'Export events',
                                                  filename)
        if filename == '':
            return

        self.filename = filename
        short_filename = short_strings(basename(self.filename))
        self.idx_filename.setText(short_filename)
177505
def export(context, keywords, module, update):
    
    logging.info(_('Export Mode'))
    database = context.obj['sense']
    none = True
    if update:
        exports = OrderedDict()
        from .executables.pe import PE
        for filename in keywords:
            module = split_ext(filename, basename=True)[0]
            with open(filename, 'rb') as stream:
                exports.update(
                    {module: PE(stream).get_export_table()})
        database.make_export(exports)
        none = False
    elif module:
        for module_name in keywords:
            funcs = database.query_module_funcs(module_name)
            if funcs:
                none = False
                print(', '.join(map(str, funcs)))
            else:
                logging.warning(_('No function for module: %s'),
                                module_name)
    else:
        for func_name in keywords:
            module_name = database.query_func_module(func_name)
            if module_name:
                none = False
                print(repr(module_name))
            else:
                logging.warning(_('No module for function: %s'),
                                func_name)
    sys.exit(1 if none else 0)
15415
def database_to_excel(engine, excel_file_path):
    
    from sqlalchemy import MetaData, select

    metadata = MetaData()
    metadata.reflect(engine)

    writer = pd.ExcelWriter(excel_file_path)
    for table in metadata.tables.values():
        sql = select([table])
        df = pd.read_sql(sql, engine)
        df.to_excel(writer, table.name, index=False)

    writer.save()
942868
def export_csv_action(description="Export selected objects as CSV file", fields=None, exclude=None, header=True):
    

    def export_as_csv(modeladmin, request, queryset):
        """Generic csv export admin action.

        based on http://djangosnippets.org/snippets/1697/

        """
        opts = modeladmin.model._meta
        field_names = set([field.name for field in opts.fields])
        if fields:
            fieldset = set(fields)
            field_names = field_names & fieldset
        elif exclude:
            excludeset = set(exclude)
            field_names = field_names - excludeset

        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename=%s.csv' % str(opts).replace('.', '_')

        writer = csv.writer(response)
        if header:
            writer.writerow(list(field_names))
        for obj in queryset:
            writer.writerow([str(getattr(obj, field)) for field in field_names])
        return response

    export_as_csv.short_description = description
    return export_as_csv
1200789
def getsavefilename(parent=None, caption='', basedir='', filters='',
                    selectedfilter='', options=None):
    """"""
    return _qfiledialog_wrapper('getSaveFileName', parent=parent,
                                caption=caption, basedir=basedir,
                                filters=filters, selectedfilter=selectedfilter,
                                options=options)
1334937
function saveNameToExportMap(index, def, exportsMap) {
    if (exportsMap) {
        if (def.exportAs)
            exportsMap[def.exportAs] = index;
        if (def.template)
            exportsMap[''] = index;
    }
}
141753
def _export(self, collection):
        
        fieldnames = collection[0].keys()
        faux_csv = ','.join(fieldnames) + '\r\n'
        for resource in collection:
            faux_csv += ','.join((str(x) for x in resource.values())) + '\r\n'
        response = make_response(faux_csv)
        response.mimetype = 'text/csv'
        return response
795200
def _as_document(self, dataset):
        
        assert isinstance(dataset, Dataset)

        doc = super(self.__class__, self)._as_document(dataset)

        # SQLite FTS can't find terms with `-`, replace it with underscore here and while searching.
        # See http://stackoverflow.com/questions/3865733/how-do-i-escape-the-character-in-sqlite-fts3-queries
        doc['keywords'] = doc['keywords'].replace('-', '_')
        doc['doc'] = doc['doc'].replace('-', '_')
        doc['title'] = doc['title'].replace('-', '_')
        return doc
780852
def to_table(self, filter_function=None):
        """"""
        table = []
        for p in self:
            if filter_function is not None and filter_function(p): continue
            table.append([p.basename, p.symbol, p.Z_val, p.l_max, p.l_local, p.xc, p.type])
        return tabulate(table, headers= ["basename", "symbol", "Z_val", "l_max", "l_local", "XC", "type"],
                        tablefmt="grid")
1370470
def format_name(self):
        '''
        
        '''
        if not hasattr(self.module, '__func_alias__'):
            # Resume normal sphinx.ext.autodoc operation
            return super(FunctionDocumenter, self).format_name()

        if not self.objpath:
            # Resume normal sphinx.ext.autodoc operation
            return super(FunctionDocumenter, self).format_name()

        if len(self.objpath) > 1:
            # Resume normal sphinx.ext.autodoc operation
            return super(FunctionDocumenter, self).format_name()

        # Use the salt func aliased name instead of the real name
        return self.module.__func_alias__.get(self.objpath[0], self.objpath[0])
1050373
def __get_datasetname(d, filename):
    
    try:
        filename = d["dataSetName"]
    except KeyError:
        logger_excel.info("get_datasetname: KeyError: No dataSetName found. Reverting to: {}".format(filename))
    return filename
800686
def export_to_xlsx(table, filename_or_fobj=None, sheet_name="Sheet1", *args, **kwargs):
    """"""

    workbook = Workbook()
    sheet = workbook.active
    sheet.title = sheet_name
    prepared_table = prepare_to_export(table, *args, **kwargs)

    # Write header
    field_names = next(prepared_table)
    for col_index, field_name in enumerate(field_names):
        cell = sheet.cell(row=1, column=col_index + 1)
        cell.value = field_name

    # Write sheet rows
    _convert_row = _python_to_cell(list(map(table.fields.get, field_names)))
    for row_index, row in enumerate(prepared_table, start=1):
        for col_index, (value, number_format) in enumerate(_convert_row(row)):
            cell = sheet.cell(row=row_index + 1, column=col_index + 1)
            cell.value = value
            if number_format is not None:
                cell.number_format = number_format

    return_result = False
    if filename_or_fobj is None:
        filename_or_fobj = BytesIO()
        return_result = True

    source = Source.from_file(filename_or_fobj, mode="wb", plugin_name="xlsx")
    workbook.save(source.fobj)
    source.fobj.flush()

    if return_result:
        source.fobj.seek(0)
        result = source.fobj.read()
    else:
        result = source.fobj

    if source.should_close:
        source.fobj.close()

    return result
211738
def export_to_json(
    table, filename_or_fobj=None, encoding="utf-8", indent=None, *args, **kwargs
):
    
    # TODO: will work only if table.fields is OrderedDict

    fields = table.fields
    prepared_table = prepare_to_export(table, *args, **kwargs)
    field_names = next(prepared_table)
    data = [
        {
            field_name: _convert(value, fields[field_name], *args, **kwargs)
            for field_name, value in zip(field_names, row)
        }
        for row in prepared_table
    ]

    result = json.dumps(data, indent=indent)
    if type(result) is six.text_type:  # Python 3
        result = result.encode(encoding)

    if indent is not None:
        # clean up empty spaces at the end of lines
        result = b"\n".join(line.rstrip() for line in result.splitlines())

    return export_data(filename_or_fobj, result, mode="wb")
169823
def _get_related_exporter(self, related_obj, column):
        
        result = column.get('sqla_xls_exporter')
        if result is None:
            worksheet = self.book.create_sheet(
                title=column.get('label', 'default title')
            )
            result = column['sqla_xls_exporter'] = SqlaXlsExporter(
                related_obj.__class__,
                worksheet=worksheet
            )
        return result
1341885
def export(self, xformat='csv'):
        """"""
        if self.annot is None:  # remove if buttons are disabled
            self.parent.statusBar().showMessage('No score file loaded')
            return

        if xformat == 'csv':
            filename = splitext(self.annot.xml_file)[0] + '.csv'
            filename, _ = QFileDialog.getSaveFileName(self, 'Export stages',
                                                      filename,
                                                      'Sleep stages (*.csv)')
        if 'remlogic' in xformat:
            filename = splitext(self.annot.xml_file)[0] + '.txt'
            filename, _ = QFileDialog.getSaveFileName(self, 'Export stages',
                                                      filename,
                                                      'Sleep stages (*.txt)')
        if filename == '':
            return

        self.annot.export(filename, xformat=xformat)