Export database to excel.

    :param engine: 
    :param excel_file_path:
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()
698906
def dump_database(self, file_path, database=None, tables=None):
        
        # Change database if needed
        if database:
            self.change_db(database)

        # Set table
        if not tables:
            tables = self.tables

        # Retrieve and join dump statements
        statements = [self.dump_table(table) for table in tqdm(tables, total=len(tables), desc='Generating dump files')]
        dump = 'SET FOREIGN_KEY_CHECKS=0;' + '\n'.join(statements) + '\nSET FOREIGN_KEY_CHECKS=1;'

        # Write dump statements to sql file
        file_path = file_path if file_path.endswith('.sql') else file_path + '.sql'
        write_text(dump, file_path)
        return file_path
637290
def _save_xls(self, filepath):
        

        Interface = self.type2interface["xls"]

        workbook = xlwt.Workbook()
        interface = Interface(self.grid.code_array, workbook)
        interface.from_code_array()

        try:
            workbook.save(filepath)

        except IOError, err:
            try:
                post_command_event(self.main_window, self.StatusBarMsg,
                                   text=err)
            except TypeError:
                # The main window does not exist any more
                pass
1083533
def _write_export(export, file_obj=None):
    

    if file_obj is None:
        return export

    if hasattr(file_obj, 'write'):
        out_file = file_obj
    else:
        out_file = open(file_obj, 'wb')
    try:
        out_file.write(export)
    except TypeError:
        out_file.write(export.encode('utf-8'))

    out_file.close()

    return export
1064600
def export_xlsx(wb, output, fn):
    
    wb.close()
    output.seek(0)
    response = HttpResponse(output.read(), content_type="application/vnd.ms-excel")
    cd = codecs.encode('attachment;filename=%s' % fn, 'utf-8')
    response['Content-Disposition'] = cd
    return response
566460
def pgexport(
    database_uri,
    table_name,
    filename,
    encoding="utf-8",
    dialect=csv.excel,
    callback=None,
    timeout=0.1,
    chunk_size=8388608,
):
    

    if isinstance(dialect, six.text_type):
        dialect = csv.get_dialect(dialect)

    # Prepare the `psql` command to be executed to export data
    command = get_psql_copy_command(
        database_uri=database_uri,
        direction="TO",
        encoding=encoding,
        header=None,  # Needed when direction = 'TO'
        table_name=table_name,
        dialect=dialect,
    )
    fobj = open_compressed(filename, mode="wb")
    try:
        process = subprocess.Popen(
            shlex.split(command),
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        total_written = 0
        data = process.stdout.read(chunk_size)
        while data != b"":
            written = fobj.write(data)
            total_written += written
            if callback:
                callback(written, total_written)
            data = process.stdout.read(chunk_size)
        stdout, stderr = process.communicate()
        if stderr != b"":
            raise RuntimeError(stderr.decode("utf-8"))

    except FileNotFoundError:
        raise RuntimeError("Command `psql` not found")

    except BrokenPipeError:
        raise RuntimeError(process.stderr.read().decode("utf-8"))

    return {"bytes_written": total_written}
164897
def export(outfile):
    """"""

    if not nav:
        sys.exit(1)

    ecode = 0
    savelist = list()
    for imageId in imagelist:

        try:
            record = {}
            record['image'] = {}
            record['image']['imageId'] = imageId
            record['image']['imagedata'] = contexts['anchore_db'].load_image_new(imageId)
        
            savelist.append(record)
        except Exception as err:
            anchore_print_err("could not find record for image ("+str(imageId)+")")
            ecode = 1

    if ecode == 0:
        try:
            if outfile == '-':
                print json.dumps(savelist, indent=4)
            else:
                with open(outfile, 'w') as OFH:
                    OFH.write(json.dumps(savelist))
        except Exception as err:
            anchore_print_err("operation failed: " + str(err))
            ecode = 1

    sys.exit(ecode)
553862
def sqlite_to_csv(
    input_filename,
    table_name,
    output_filename,
    dialect=csv.excel,
    batch_size=10000,
    encoding="utf-8",
    callback=None,
    query=None,
):
    """"""

    # TODO: should be able to specify fields
    # TODO: should be able to specify custom query

    if isinstance(dialect, six.text_type):
        dialect = csv.get_dialect(dialect)

    if query is None:
        query = "SELECT * FROM {}".format(table_name)
    connection = sqlite3.Connection(input_filename)
    cursor = connection.cursor()
    result = cursor.execute(query)
    header = [item[0] for item in cursor.description]
    fobj = open_compressed(output_filename, mode="w", encoding=encoding)
    writer = csv.writer(fobj, dialect=dialect)
    writer.writerow(header)
    total_written = 0
    for batch in rows.plugins.utils.ipartition(result, batch_size):
        writer.writerows(batch)
        written = len(batch)
        total_written += written
        if callback:
            callback(written, total_written)
    fobj.close()
85689
function Engine(sqlfilepath,callback) {                                                      
	this._resourceFields={};
	this._tags={};
	this._db=new TransactionDatabase( new sqlite3.Database(sqlfilepath) );

	var self=this;
	self._db.run("CREATE TABLE tag (name TEXT PRIMARY KEY, resource_count INTEGER, last_used_at INTEGER)",[], (err) => {
		self._db.serialize( () => {
			if (!err) {
				/* 
				if no error, the table did not exist, so let's create the remaining tables since this db is not yet initialized
				*/
				
				/*
				following line is commented since i get foreign key errors although i shouldn't. 
				there must be some subtility i miss in parallel operations, although they appear to run
				all in the correct order. i finally don't care too much, since the code ensures consistency 
				pretty much by its own.
				*/
				//self._db.run("PRAGMA foreign_keys = '1'");
				self._db.run("CREATE TABLE resource (_url TEXT, _created_at INTEGER, _modified_at INTEGER, _path TEXT)");
				self._db.run("CREATE UNIQUE INDEX resource_path on resource (_path)");
				self._db.run("CREATE TABLE tree_idx (desc_id INTEGER, anc_id INTEGER, FOREIGN KEY (anc_id) REFERENCES resource (rowid), FOREIGN KEY (desc_id) REFERENCES resource (rowid))");
				self._db.run("CREATE UNIQUE INDEX tree_descendant on tree_idx (desc_id,anc_id)");
				self._db.run("CREATE INDEX tree_ancestor on tree_idx (anc_id)");
				self._db.run("CREATE TABLE resource_field (name TEXT, type INTEGER)");
				self._db.run("CREATE TABLE resource_tag (resource_id INTEGER, tag_id INTEGER, tag_path TEXT, comment TEXT, FOREIGN KEY (resource_id) REFERENCES resource (rowid), FOREIGN KEY (tag_id) REFERENCES tag (rowid))");
				self._db.run("CREATE UNIQUE INDEX resource_tag_relation on resource_tag (resource_id,tag_id)");
				self._db.run("CREATE INDEX resource_tag_by_tag on resource_tag (tag_id)");
				self._db.run("CREATE INDEX resource_tag_by_tagpath on resource_tag (tag_path)");
				self._db.run("CREATE TABLE meta (key TEXT, value TEXT)");
				self._db.run("INSERT INTO meta (key,value) VALUES ('format_version','1')");
			}
			/*
			load all resource fields, which are cached.
			*/
			self._db.each("SELECT name,type FROM resource_field", (err, row) => {
				self._resourceFields[row.name]=row.type;
			}, (err) => {
				/*
				load all tags, which are cached as well.
				*/
				self._db.each("SELECT rowid,name,resource_count,last_used_at FROM tag", (err, row) => {
					self._tags[row.name]=row;
				}, (err) => {
					if (callback) callback(err,self);
				});
			});
		});
	});
	
	/*
	Qed version of the engine API: all public methods of the engine are replicated on the engine.q object, but
	returning a promise istead of calling a callback.
	*/
	this.q={
		cb: self,
		define: (fieldName,fieldType) => {
			var d=Q.defer();
			self.define(fieldName,fieldType, (err) => {
				if (err) d.reject(err);
				else d.resolve();
			});
			return d.promise;
		},
		loadBulk: (data) => {
			var d=Q.defer();
			self.loadBulk(data, (err) => {
				if (err) d.reject(err);
				else d.resolve();
			});
			return d.promise;
		},
		update: (url,tags,data) => {
			var d=Q.defer();
			self.update(url,tags,data, (err,id) => {
				if (err) d.reject(err);
				else d.resolve(id);
			});
			return d.promise;
		},
		remove: (url) => {
			var d=Q.defer();
			self.remove(url, (err,id) => {
				if (err) d.reject(err);
				else d.resolve(id);
			});
			return d.promise;
		},                                   
		removeBulk: (urlList) => {
			var d=Q.defer();
			self.removeBulk(urlList, (err,id) => {
				if (err) d.reject(err);
				else d.resolve(id);
			});
			return d.promise;
		},                                   
		rename: (url,newUrl,renameDescendants) => {
			var d=Q.defer();
			self.rename(url, newUrl, renameDescendants, (err,id) => {
				if (err) d.reject(err);
				else d.resolve(id);
			});
			return d.promise;
		},
		findResources: (tags,orderBy,limit,offset) => {
			var d=Q.defer();
			self.findResources(tags,orderBy,limit,offset, (err,res) => {
				if (err) d.reject(err);
				else d.resolve(res);
			});
			return d.promise;
		},
		getResource: (url) => {
			var d=Q.defer();
			self.getResource(url, (err,res) => {
				if (err) d.reject(err);
				else d.resolve(res);
			});
			return d.promise;
		},
		getBulk: (urlList) => {
			var d=Q.defer();
			self.getBulk(urlList, (err,res) => {
				if (err) d.reject(err);
				else d.resolve(res);
			});
			return d.promise;
		},
		tagCloud: (tags,limit,useOr) => {
			var d=Q.defer();
			self.tagCloud(tags,limit,useOr, (err,res) => {
				if (err) d.reject(err);
				else d.resolve(res);
			});
			return d.promise;
		},
		getSuggestions: (prefix,exclude,limit,offset,minWeight) => {
			var d=Q.defer();
			self.getSuggestions(prefix,exclude,limit,offset,minWeight, (err,res) => {
				if (err) d.reject(err);
				else d.resolve(res);
			});
			return d.promise;
		},
		clear: () => {
			var d=Q.defer();
			self.clear( (err,res) => {
				if (err) d.reject(err);
				else d.resolve(res);
			});
			return d.promise;
		}
	};
	
	/*
	ensure that whatever API you are using (the callback API or the Qed one), you will
	always be able to do:
		engine.cb.someMethod()
	and:
		engine.q.someMethod()
	getting explicitely the desired version of the method.
	*/
	this.q.q=this.q;
	this.cb=this;
	
}
1364059
def export_file(self, data_object, destination_directory=None,
                    destination_filename=None, retry=False,
                    export_metadata=False, export_raw_file=True):
        
        if not destination_directory:
            destination_directory = os.getcwd()

        # We get filename from the dataobject
        if not destination_filename:
            destination_filename = data_object['value']['filename']

        destination_file_url = os.path.join(destination_directory,
                                            destination_filename)

        logger.info('Exporting file %s@%s ...' % (
            data_object['value']['filename'],
            data_object['uuid']))

        if export_raw_file:
            destination = File(
                destination_file_url, self.storage_settings, retry=retry)
            if destination.exists():
                raise FileAlreadyExistsError(
                    'File already exists at %s' % destination_file_url)
            logger.info('...copying file to %s' % (
                destination.get_url()))

            # Copy from the first file location
            file_resource = data_object.get('value')
            md5 = file_resource.get('md5')
            source_url = data_object['value']['file_url']
            File(source_url, self.storage_settings, retry=retry).copy_to(
                destination, expected_md5=md5)
            data_object['value'] = self._create_new_file_resource(
                data_object['value'], destination.get_url())
        else:
            logger.info('...skipping raw file')

        if export_metadata:
            data_object['value'].pop('link', None)
            data_object['value'].pop('upload_status', None)
            destination_metadata_url = os.path.join(
                destination_file_url + '.metadata.yaml')
            logger.info('...writing metadata to %s' % destination_metadata_url)
            metadata = yaml.safe_dump(data_object, default_flow_style=False)
            metadata_file = File(destination_metadata_url,
                                 self.storage_settings, retry=retry)
            metadata_file.write(metadata)
        else:
            logger.info('...skipping metadata')

        logger.info('...finished file export')
826338
def connect_engine(self):
        
        try:
            self.connection = self.engine.connect()
            return True
        except sa.exc.OperationalError as opex:
            LOG.fatal("Could not connect to the database. The error was: '%s'",
                      str(opex))
        return False
267831
def export(self, elec_file):
        
        elec_file = Path(elec_file)
        if elec_file.suffix == '.csv':
            sep = ', '
        elif elec_file.suffix == '.sfp':
            sep = ' '

        with elec_file.open('w') as f:
            for one_chan in self.chan:
                values = ([one_chan.label, ] +
                          ['{:.3f}'.format(x) for x in one_chan.xyz])
                line = sep.join(values) + '\n'
                f.write(line)
893196
def export_csv_file(self, directory, filename):
        
        bpmn_csv_export.BpmnDiagramGraphCsvExport.export_process_to_csv(self, directory, filename)
54885
public void exportObjects2Excel(String templatePath, List<?> data, Class clazz, OutputStream os)
            throws Excel4JException {

        exportObjects2Excel(templatePath, 0, data, null, clazz, true, os);
    }
1076436
def dump_orm_object_as_insert_sql(engine: Engine,
                                  obj: object,
                                  fileobj: TextIO) -> None:
    
    # literal_query = make_literal_query_fn(engine.dialect)
    insp = inspect(obj)
    # insp: an InstanceState
    # http://docs.sqlalchemy.org/en/latest/orm/internals.html#sqlalchemy.orm.state.InstanceState  # noqa
    # insp.mapper: a Mapper
    # http://docs.sqlalchemy.org/en/latest/orm/mapping_api.html#sqlalchemy.orm.mapper.Mapper  # noqa

    # Don't do this:
    #   table = insp.mapper.mapped_table
    # Do this instead. The method above gives you fancy data types like list
    # and Arrow on the Python side. We want the bog-standard datatypes drawn
    # from the database itself.
    meta = MetaData(bind=engine)
    table_name = insp.mapper.mapped_table.name
    # log.debug("table_name: {}", table_name)
    table = Table(table_name, meta, autoload=True)
    # log.debug("table: {}", table)

    # NewRecord = quick_mapper(table)
    # columns = table.columns.keys()
    query = select(table.columns)
    # log.debug("query: {}", query)
    for orm_pkcol in insp.mapper.primary_key:
        core_pkcol = table.columns.get(orm_pkcol.name)
        pkval = getattr(obj, orm_pkcol.name)
        query = query.where(core_pkcol == pkval)
    # log.debug("query: {}", query)
    cursor = engine.execute(query)
    row = cursor.fetchone()  # should only be one...
    row_dict = dict(row)
    # log.debug("obj: {}", obj)
    # log.debug("row_dict: {}", row_dict)
    statement = table.insert(values=row_dict)
    # insert_str = literal_query(statement)
    insert_str = get_literal_query(statement, bind=engine)
    writeline_nl(fileobj, insert_str)
178298
def export_to_file(self, filename):
        
        instr_json = self.export_struct()

        with open(filename, 'w') as fp:
            json.dump(instr_json, fp, indent=2)
61588
def dump_engines(target=sys.stderr):
    """"""
    print("Available templating engines:", file=target)

    width = max(len(engine) for engine in engines.engines)
    for handle, engine in sorted(engines.engines.items()):
        description = engine.__doc__.split('\n', 0)[0]
        print("  %-*s  -  %s" % (width, handle, description), file=target)