Python pandas.ExcelWriter() Examples

The following are 30 code examples for showing how to use pandas.ExcelWriter(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module pandas , or try the search function .

Example 1
Project: scVI   Author: YosefLab   File: posterior_utils.py    License: MIT License 6 votes vote down vote up
def save_cluster_xlsx(
    filepath: str, de_results: List[pd.DataFrame], cluster_names: List
):
    """Saves multi-clusters DE in an xlsx sheet

    Parameters
    ----------
    filepath
        xslx save path
    de_results
        list of pandas Dataframes for each cluster
    cluster_names
        list of cluster names
    """
    writer = pd.ExcelWriter(filepath, engine="xlsxwriter")
    for i, x in enumerate(cluster_names):
        de_results[i].to_excel(writer, sheet_name=str(x))
    writer.close() 
Example 2
Project: skan   Author: jni   File: io.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def write_excel(filename, **kwargs):
    """Write data tables to an Excel file, using kwarg names as sheet names.
    
    Parameters
    ----------
    filename : str
        The filename to write to.
    kwargs : dict
        Mapping from sheet names to data.
    """
    writer = pd.ExcelWriter(filename)
    for sheet_name, obj in kwargs.items():
        if isinstance(obj, dict):
            obj = _params_dict_to_dataframe(obj)
        if isinstance(obj, pd.DataFrame):
            obj.to_excel(writer, sheet_name=sheet_name)
    writer.save()
    writer.close() 
Example 3
Project: tweets-collector   Author: motazsaad   File: text2xlsx.py    License: Apache License 2.0 6 votes vote down vote up
def export_text2xlsx(infile, outfile, field_delimiter, number):
    df = pd.read_csv(infile, delimiter=field_delimiter, engine='python')
    rows_number = df.shape[0]
    if rows_number > number:
        data_frames = split_dataframe(df, number)
        frame_number = 1
        for frame in data_frames:
            filename, ext = os.path.splitext(outfile)
            excel_file = "{}_{}.xlsx".format(filename, frame_number)
            writer = ExcelWriter(excel_file, engine='xlsxwriter')
            frame.to_excel(writer, 'sheet1')
            writer.save()
            frame_number += 1
    else:
        writer = ExcelWriter(outfile)
        df.to_excel(writer, 'sheet1')
        writer.save() 
Example 4
Project: pybel   Author: pybel   File: spia.py    License: MIT License 6 votes vote down vote up
def spia_matrices_to_excel(spia_matrices: SPIADataFrames, path: str) -> None:
    """Export a SPIA data dictionary into an Excel sheet at the given path.

    .. note::

        # The R import should add the values:
        # ["nodes"] from the columns
        # ["title"] from the name of the file
        # ["NumberOfReactions"] set to "0"
    """
    writer = pd.ExcelWriter(path, engine='xlsxwriter')

    for relation, df in spia_matrices.items():
        df.to_excel(writer, sheet_name=relation, index=False)

    # Save excel
    writer.save() 
Example 5
Project: CityEnergyAnalyst   Author: architecture-building-systems   File: reporting.py    License: MIT License 6 votes vote down vote up
def full_report_to_xls(tsd, output_folder, basename):
    """ this function is to write a full report to an ``*.xls`` file containing all intermediate and final results of a
    single building thermal loads calculation"""

    df = pd.DataFrame(tsd)

    # Create a Pandas Excel writer using XlsxWriter as the engine.
    #timestamp = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
    #output_path = os.path.join(output_folder,"%(basename)s-%(timestamp)s.xls" % locals())
    output_path = os.path.join(output_folder, "%(basename)s.xls" % locals())
    writer = pd.ExcelWriter(output_path, engine='xlwt')

    df.to_excel(writer, na_rep='NaN')

    # Close the Pandas Excel writer and output the Excel file.
    writer.save()
    writer.close() 
Example 6
Project: staramr   Author: phac-nml   File: Search.py    License: Apache License 2.0 6 votes vote down vote up
def _resize_columns(self, sheetname_dataframe, writer, max_width, text_wrap=True):
        """
        Resizes columns in workbook.
        :param sheetname_dataframe: A map mapping the sheet name to a dataframe.
        :param writer: The ExcelWriter, which the worksheets already added using writer.to_excel
        :param max_width: The maximum width of the columns.
        :param text_wrap: Whether or not to turn on text wrapping if columns surpass max_width.
        :return: None
        """
        workbook = writer.book
        wrap_format = workbook.add_format({'text_wrap': text_wrap})
        for name in sheetname_dataframe:
            for i, width in enumerate(self._get_col_widths(sheetname_dataframe[name])):
                if width > max_width:
                    writer.sheets[name].set_column(i, i, width=max_width, cell_format=wrap_format)
                else:
                    writer.sheets[name].set_column(i, i, width=width) 
Example 7
Project: RLs   Author: StepNeverStop   File: recorder.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, kwargs, *, cp_dir, log_dir, excel_dir, logger2file):
        self.log_dir = log_dir
        self.writer = tf.summary.create_file_writer(log_dir)
        # self.writer.set_as_default()
        self.checkpoint = tf.train.Checkpoint(**kwargs)
        self.saver = tf.train.CheckpointManager(self.checkpoint, directory=cp_dir, max_to_keep=5, checkpoint_name='ckpt')
        self.excel_writer = pd.ExcelWriter(excel_dir + '/data.xlsx')
        self.logger = self.create_logger(
            name='logger',
            console_level=logging.INFO,
            console_format='%(levelname)s : %(message)s',
            logger2file=logger2file,
            file_name=log_dir + 'log.txt',
            file_level=logging.WARNING,
            file_format='%(lineno)d - %(asctime)s - %(module)s - %(funcName)s - %(levelname)s - %(message)s'
        ) 
Example 8
Project: spinalcordtoolbox   Author: neuropoly   File: sct_analyze_lesion.py    License: MIT License 6 votes vote down vote up
def pack_measures(self):
        writer = pd.ExcelWriter(self.excel_name, engine='xlwt')
        self.measure_pd.to_excel(writer, sheet_name='measures', index=False, engine='xlwt')

        # Add the total column and row
        if self.path_template is not None:
            for sheet_name in self.distrib_matrix_dct:
                if '#' in sheet_name:
                    df = self.distrib_matrix_dct[sheet_name].copy()
                    df = df.append(df.sum(numeric_only=True, axis=0), ignore_index=True)
                    df['total'] = df.sum(numeric_only=True, axis=1)
                    df.iloc[-1, df.columns.get_loc('vert')] = 'total'
                    df.to_excel(writer, sheet_name=sheet_name, index=False, engine='xlwt')
                else:
                    self.distrib_matrix_dct[sheet_name].to_excel(writer, sheet_name=sheet_name, index=False, engine='xlwt')

        # Save pickle
        self.distrib_matrix_dct['measures'] = self.measure_pd
        with open(self.pickle_name, 'wb') as handle:
            pickle.dump(self.distrib_matrix_dct, handle)

        # Save Excel
        writer.save() 
Example 9
Project: pymongo-schema   Author: pajachiet   File: export.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def write_data(self, file_descr):
        """
        Use dataframe to_excel to write into file_descr (filename) - open first if file exists.
        """
        if os.path.isfile(file_descr):
            print(file_descr, 'exists')
            # Solution to keep existing data
            book = load_workbook(file_descr)
            writer = pd.ExcelWriter(file_descr, engine='openpyxl')
            writer.book = book
            writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
            self.data_df.to_excel(writer, sheet_name='Mongo_Schema', index=True,
                                  float_format='%.2f')
            writer.save()
        else:
            self.data_df.to_excel(file_descr, sheet_name='Mongo_Schema', index=True,
                                  float_format='%.2f') 
Example 10
Project: SDGym   Author: sdv-dev   File: results.py    License: MIT License 6 votes vote down vote up
def write_results(results, summary, output):
    writer = pd.ExcelWriter(output, engine='xlsxwriter')
    cell_fmt = writer.book.add_format({
        "font_name": "Arial",
        "font_size": "10"
    })
    index_fmt = writer.book.add_format({
        "font_name": "Arial",
        "font_size": "10",
        "bold": True,
    })
    header_fmt = writer.book.add_format({
        "font_name": "Arial",
        "font_size": "10",
        "bold": True,
        "bottom": 1
    })

    add_sheet(summary, 'Number of wins per version', writer, cell_fmt, index_fmt, header_fmt)

    for version in reversed(sorted(results.keys())):
        add_sheet(results[version], version, writer, cell_fmt, index_fmt, header_fmt)

    writer.save() 
Example 11
Project: patzilla   Author: ip-tools   File: export.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def create(self):

        # A memory buffer as ExcelWriter storage backend
        buffer = BytesIO()
        self.workbook.filename = buffer

        # Create "cover" sheet
        self.write_cover_sheet()

        # Create "queries" sheet
        self.write_queries_sheet()

        # Create numberlist sheets
        self.write_numberlist_sheets()

        # Create "comments" sheet
        self.write_comments_sheet()

        # Save/persist ExcelWriter model
        self.writer.save()

        # Get hold of buffer content
        payload = buffer.getvalue()
        return payload 
Example 12
Project: ditto   Author: NREL   File: create_excel.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def write_to_excel(comp_values):
    current_dir = os.path.realpath(os.path.dirname(__file__))
    df = pd.DataFrame(comp_values)
    with pd.ExcelWriter(os.path.join(current_dir, "output" + ".xlsx")) as writer:
        for col in df:
            df1 = pd.concat([df[col], df[col].apply(pd.Series)], axis=1).drop(
                [col], axis=1
            )
            df1.to_excel(writer, sheet_name=col)
            worksheet = writer.sheets[col]
            worksheet.set_column(0, 19, 16)


# Tests for running the plots independently
# if __name__ == "__main__":
#    write_to_excel({'ieee_4node': {'cyme_output': {'1': [1.796043190045738, 5.388117303585387, 0.10784685850195197, 0.5904760366014294], '2': [2.0202605985010313, 6.518985500570162, 0.22820004614399358, 0.8158267453203445], '3': [0.2536631703405771, 0.8984713888134145, 0.06581202655980385, 0.24831713333607722], '4': [0.5340964354229437, 2.3119539172019614, 0.23396047634518685, 0.46239954705589636]}, 'demo_output': {}, 'gridlabd_output': {'sourcebus': [1.7960358301233543, 5.388107490370064, 1.6037668205527515, 6.415067282211007], 'node2': [11.615625751028661, 11.520529778987775, 9.073598525409436, 5.8609512435066655], 'node3': [1.2918305507375225, 1.2769209930818217, 1.0089298663668416, 0.6470699623879508], 'load4': [0.8640026377752124, 0.41845221416471984, 0.8640056993976751, 0.4184497947877163], 'node1': [11.95788550650638, 12.207304856874984, 9.189536257036401, 6.043847565567804]}, 'opendss_output': {'sourcebus': [0.0002463564270509644, 0.0007390394604267333, 0.00018858267905109123, 0.0007542723977164494], 'n2': [0.29564583680274237, 0.7167450994489304, 0.11638654713225582, 0.2358768460293939], 'n3': [0.06870713919610347, 0.23863115122119738, 0.048858783362332986, 0.18910852255356034], 'n4': [0.5051857600366919, 0.7781653125896516, 0.21133259350889166, 0.4141945608522559]}, 'synergi_output': {'node_61746791326': [0.000999999415454687, 0.0009999923015324673, 0.0009999996415073831, 0.0009999921771822826], 'node_61746791327': [1.4052433405517772, 0.8534261345199505, 1.100207413576314, 0.09925701086833777], 'node_61746839533': [0.5767771891663984, 1.2140898058567755, 0.5400898631419725, 1.138540681909626], 'node_61746842036': [2.2802968553458975, 1.9930774142792114, 1.8176517572334512, 1.1452767401123385]}}, 'ieee_13node': {'cyme_output': {'650': [1.6442002249862027, 2.525071217368887, 0.00175590064769382, 0.013818660541591976], '633': [2.191962671993786, 2.7645145724914206, 0.13502678340376117, 0.30258402028428943], '634': [0.03373885959967424, 0.0437948202860033, 0.006851233217346727, 0.01281928879314106], '7': [1.6444948113338582, 2.5248296649991535, 0.0027565424317121945, 0.014811194353743895], 'rg60': [1.6444956621823732, 2.524829864977333, 0.002756707027920302, 0.014813876873885912], '632': [2.1103087225772716, 2.527515777000864, 0.0791161472443358, 0.2320482533916044], '652': [1.2506186991395154, 1.2878722947329384, 1.2506186991395154, 1.2878722947329384], '611': [1.1239472985549395, 1.3770646713358636, 1.1239472985549395, 1.3770646713358636], '692': [2.631742710227492, 2.70681263013228, 0.16404792757812026, 0.44179116013620445], '645': [2.2388323604857887, 2.784026210466048, 0.1850730276433944, 0.31739303544051045], '646':[2.317657028721549, 2.949917446377885, 0.24850513527121498, 0.3676808102436452], '671': [2.630682474394549, 2.706364834017407, 0.16301316760562778, 0.44085146992520197], '675': [2.7067614833052813, 2.7173749384388346, 0.23870615585157873, 0.47708961405564254], '684': [2.6970360888981926, 2.8036701407791496, 0.23157910972791085, 0.5317115549334911], '680': [2.7200580191836536, 3.2662254613120227, 0.19824054093535326, 0.5540558678888127]}, 'demo_output': {}, 'gridlabd_output': {}, 'opendss_output': {'sourcebus': [0.17960357997560872, 0.5388107499674782, 0.16044213136336458, 0.6414216083753025], '650': [3.46173977571697e-05, 0.00027688611330264445, 0.00024463297015852746, 0.0011161493255213788], 'rg60': [0.0003803596442662037, 0.0006225803505498496, 0.0005903829452526287, 0.0014616392165030185], '633': [0.38047984831844595, 0.8729366035169337, 0.13271664569004354, 0.28972479926771977], '634': [0.010133922766079825, 0.020570453379602505, 0.006830751758597249, 0.012931935773494248], '671': [0.6108771018713602, 1.3265863413420522, 0.16093756369535386, 0.42423496513300524], '645': [0.4373080269407039, 0.8584390204064538, 0.18280284255143675, 0.32024566175842095], '646': [0.536560726260114, 0.9883607573047537, 0.24564544687076215, 0.36912074589189336], '692': [0.6119751654440972, 1.3274110796789444, 0.16196524206540175, 0.4251679482288616], '675': [0.7447836834016821, 1.3496142794655475, 0.20882248763406844, 0.46165856154276824], '611': [0.47109807838681994, 0.8597942885112269, 0.47109807838681994, 0.8597942885112269], '652': [0.5900525671135924, 0.8394468662430931, 0.5900525671135924, 0.8394468662430931], '670': [0.3852338293138269, 0.8975161336344963, 0.1039477429886314, 0.2879817616207214], '632': [0.2799093266146708, 0.6803831271514527, 0.07670340676752073, 0.21819919790776035], '680': [0.7346431542735055, 1.6877642140995293, 0.19615949605780691, 0.5372620670065573], '684': [0.7244901189090343, 1.397819420078607, 0.22833210323410577, 0.4698019455814719]}, 'synergi_output': {}}}) 
Example 13
Project: evo   Author: MichaelGrupp   File: pandas_bridge.py    License: GNU General Public License v3.0 6 votes vote down vote up
def save_df_as_table(df, path,
                     format_str=SETTINGS.table_export_format,
                     transpose=SETTINGS.table_export_transpose,
                     confirm_overwrite=False):
    if confirm_overwrite and not user.check_and_confirm_overwrite(path):
        return
    if transpose:
        df = df.T
    if format_str == "excel":
        # requires xlwt and/or openpyxl to be installed
        with pd.ExcelWriter(path) as writer:
            df.to_excel(writer)
    else:
        getattr(df, "to_" + format_str)(path)
    logger.debug("{} table saved to: {}".format(
        format_str, path)) 
Example 14
Project: modin   Author: modin-project   File: test_io.py    License: Apache License 2.0 6 votes vote down vote up
def test_to_excel():
    modin_df = create_test_modin_dataframe()
    pandas_df = create_test_pandas_dataframe()

    TEST_EXCEL_DF_FILENAME = "test_df.xlsx"
    TEST_EXCEL_pandas_FILENAME = "test_pandas.xlsx"

    modin_writer = pandas.ExcelWriter(TEST_EXCEL_DF_FILENAME)
    pandas_writer = pandas.ExcelWriter(TEST_EXCEL_pandas_FILENAME)

    modin_df.to_excel(modin_writer)
    pandas_df.to_excel(pandas_writer)

    modin_writer.save()
    pandas_writer.save()

    assert assert_files_eq(TEST_EXCEL_DF_FILENAME, TEST_EXCEL_pandas_FILENAME)

    teardown_test_file(TEST_EXCEL_DF_FILENAME)
    teardown_test_file(TEST_EXCEL_pandas_FILENAME) 
Example 15
Project: pyam   Author: IAMconsortium   File: test_io.py    License: Apache License 2.0 6 votes vote down vote up
def test_io_xlsx(test_df, meta_args):
    # add column to `meta`
    test_df.set_meta(['a', 'b'], 'string')

    # write to xlsx (direct file name and ExcelWriter, see bug report #300)
    file = 'testing_io_write_read.xlsx'
    for f in [file, pd.ExcelWriter(file)]:
        test_df.to_excel(f, **meta_args[0])
        if isinstance(f, pd.ExcelWriter):
            f.close()

        # read from xlsx
        import_df = IamDataFrame(file, **meta_args[1])

        # assert that IamDataFrame instances are equal and delete file
        assert_iamframe_equal(test_df, import_df)
        os.remove(file) 
Example 16
Project: pyam   Author: IAMconsortium   File: core.py    License: Apache License 2.0 6 votes vote down vote up
def export_meta(self, excel_writer, sheet_name='meta'):
        """Write the 'meta' indicators of this object to an Excel sheet

        Parameters
        ----------
        excel_writer : str, path object or ExcelWriter object
            any valid string path, :class:`pathlib.Path`
            or :class:`pandas.ExcelWriter`
        sheet_name : str
            name of sheet which will contain dataframe of 'meta' indicators
        """
        if not isinstance(excel_writer, pd.ExcelWriter):
            close = True
            excel_writer = pd.ExcelWriter(excel_writer)
        write_sheet(excel_writer, sheet_name, self.meta, index=True)
        if close:
            excel_writer.close() 
Example 17
Project: CO2MPAS-TA   Author: JRCSTU   File: sync.py    License: European Union Public License 1.1 6 votes vote down vote up
def template(output_file, cycle_type, gear_box_type, wltp_class):
    """
    Writes a sample template OUTPUT_FILE.

    OUTPUT_FILE: SYNCING input template file (.xlsx). [default: ./datasync.xlsx]
    """

    import pandas as pd
    from co2mpas.core.model.physical.cycle import dsp
    theoretical = sh.selector(['times', 'velocities'], dsp(inputs=dict(
        cycle_type=cycle_type.upper(), gear_box_type=gear_box_type,
        wltp_class=wltp_class, downscale_factor=0
    ), outputs=['times', 'velocities'], shrink=True))
    base = dict.fromkeys((
        'times', 'velocities', 'target gears', 'engine_speeds_out',
        'engine_coolant_temperatures', 'co2_normalization_references',
        'alternator_currents', 'battery_currents', 'target fuel_consumptions',
        'target co2_emissions', 'target engine_powers_out'
    ), [])
    data = dict(theoretical=theoretical, dyno=base, obd=base)
    os.makedirs(osp.dirname(output_file), exist_ok=True)
    with pd.ExcelWriter(output_file) as writer:
        for k, v in data.items():
            pd.DataFrame(v).to_excel(writer, k, index=False)
    return data 
Example 18
Project: CO2MPAS-TA   Author: JRCSTU   File: excel.py    License: European Union Public License 1.1 6 votes vote down vote up
def _clone_excel(file_name):
    from urllib.error import URLError
    import openpyxl
    try:
        from urllib.request import urlopen
        book = openpyxl.load_workbook(urlopen(file_name))
    except (ValueError, URLError):
        with open(file_name, 'rb') as file:
            book = openpyxl.load_workbook(file)
    import io
    import pandas as pd
    fd = io.BytesIO()
    # noinspection PyTypeChecker
    writer = pd.ExcelWriter(
        fd, engine='openpyxl', optimized_write=True, write_only=True
    )
    writer.book = book
    writer.sheets.update(dict((ws.title, ws) for ws in book.worksheets))
    return writer, fd 
Example 19
Project: workload-collocation-agent   Author: intel   File: runner_analyzer.py    License: Apache License 2.0 5 votes vote down vote up
def multiple_dfs(self, df_list, sheets, file_name, spaces):
        writer = pd.ExcelWriter(file_name, engine='xlsxwriter')
        row = 0
        for dataframe in df_list:
            dataframe.to_excel(writer, sheet_name=sheets, startrow=row, startcol=0)
            row = row + len(dataframe.index) + spaces + 1
        writer.save() 
Example 20
Project: workload-collocation-agent   Author: intel   File: runner_analyzer.py    License: Apache License 2.0 5 votes vote down vote up
def export_to_xls(self):
        logging.debug("Saving xls to {} for experiment {}".format(self.export_file_path,
                                                                  self.experiment_index))

        runner_analyzer_results_dir = os.path.join(self.experiment_meta.data_path,
                                                   'runner_analyzer')
        if not os.path.isdir(runner_analyzer_results_dir):
            os.mkdir(runner_analyzer_results_dir)

        with pd.ExcelWriter(os.path.join(runner_analyzer_results_dir,
                                         'tasks_summaries_{}.xlsx'.format(
                                             self.experiment_index))) as writer:
            self.tasks_summaries[0].to_excel(writer, sheet_name='BASELINE')
            self.tasks_summaries[1].to_excel(writer, sheet_name='KUBERNETES_BASELINE')
            self.tasks_summaries[2].to_excel(writer, sheet_name='WCA-SCHEDULER')

        with pd.ExcelWriter(os.path.join(runner_analyzer_results_dir,
                                         'node_summaries_{}.xlsx'.format(
                                             self.experiment_index))) as writer:
            self.node_summaries[0].to_excel(writer, sheet_name='BASELINE')
            self.node_summaries[1].to_excel(writer, sheet_name='KUBERNETES_BASELINE')
            self.node_summaries[2].to_excel(writer, sheet_name='WCA-SCHEDULER')

        with pd.ExcelWriter(os.path.join(runner_analyzer_results_dir,
                                         'workloads_summaries_{}.xlsx'.format(
                                             self.experiment_index))) as writer:
            self.workloads_summaries[0].to_excel(writer, sheet_name='BASELINE')
            self.workloads_summaries[1].to_excel(writer, sheet_name='KUBERNETES_BASELINE')
            self.workloads_summaries[2].to_excel(writer, sheet_name='WCA-SCHEDULER') 
Example 21
Project: dash-recipes   Author: plotly   File: dash-download-file-link-server.py    License: MIT License 5 votes vote down vote up
def update_href(dropdown_value):
    df = pd.DataFrame({dropdown_value: [1, 2, 3]})
    relative_filename = os.path.join(
        'downloads',
        '{}-download.xlsx'.format(dropdown_value)
    )
    absolute_filename = os.path.join(os.getcwd(), relative_filename)
    writer = pd.ExcelWriter(absolute_filename)
    df.to_excel(writer, 'Sheet1')
    writer.save()
    return '/{}'.format(relative_filename) 
Example 22
Project: Table-Extractor-From-Image   Author: rohanpillai20   File: JSON-to-Excel.py    License: Apache License 2.0 5 votes vote down vote up
def exportInExcel(dataFrame,noOfRows,f):
    try:
        #Copy the text in a list
        a = copy.copy(dataFrame)
        for i in range(0, noOfRows):
            for j in range(0, len(dataFrame[i])):
                if(dataFrame[i][j]=='-'):
                    a[i][j]='-'
                else:
                    a[i][j]=dataFrame[i][j].text
        print(' ')
        #Convert the list into a pandas.DataFrame
        df = pd.DataFrame(a)
        print(df)
        
        if os.path.exists(exportPath):
            #If any excel sheet exists
            book = load_workbook(exportPath)
            writer = pd.ExcelWriter(exportPath, engine='openpyxl') 
            writer.book = book
            writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
            df.to_excel(writer, f)
            writer.save()
        else:
            #If it doesn't, then create a new file
            writer = ExcelWriter(exportPath)
            df.to_excel(writer,f)
            writer.save()
            
    except Exception as e:
        print("Exception in exportInExcel():", e)


#Main Function 
Example 23
Project: kobo-predict   Author: awemulya   File: pandas_mongo_bridge.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def export_to(self, file_path, batchsize=1000):
        self.xls_writer = ExcelWriter(file_path)

        # get record count
        record_count = self._query_mongo(count=True)

        # query in batches and for each batch create an XLSDataFrameWriter and
        # write to existing xls_writer object
        start = 0
        header = True
        while start < record_count:
            cursor = self._query_mongo(self.filter_query, start=start,
                                       limit=batchsize)

            data = self._format_for_dataframe(cursor)

            # write all cursor's data to their respective sheets
            for section_name, section in self.sections.iteritems():
                records = data[section_name]
                # TODO: currently ignoring nested repeats
                # so ignore sections that have 0 records
                if len(records) > 0:
                    # use a different group delimiter if needed
                    columns = section["columns"]
                    if self.group_delimiter != DEFAULT_GROUP_DELIMITER:
                        columns = [self.group_delimiter.join(col.split("/"))
                                   for col in columns]
                    columns = columns + self.EXTRA_COLUMNS
                    writer = XLSDataFrameWriter(records, columns)
                    writer.write_to_excel(self.xls_writer, section_name,
                                          header=header, index=False)
            header = False
            # increment counter(s)
            start += batchsize
            time.sleep(0.1)
        self.xls_writer.save() 
Example 24
Project: Pointer-Generator   Author: Sohone-Guo   File: os.py    License: MIT License 5 votes vote down vote up
def list_excel(columns, data, file_name):
    """
    # Arguments
        - columns {list}: ["a","b"]
        - data {list}:[["a-v","b-v"]["a-v1","a-v2"]]
    """
    df = pd.DataFrame(columns=columns,data=data)
    writer = pd.ExcelWriter(file_name+'.xlsx')
    df.to_excel(writer,'Sheet1')
    return "Done" 
Example 25
Project: financial_life   Author: MartinPyka   File: excel.py    License: Apache License 2.0 5 votes vote down vote up
def report(simulation, filename='report.xls'):
    """ This function generates a report as an excel sheet.
    
    simulation      the simualation that should be exported to excel
    filename        filename of the excel file
    """
    
    writer = pd.ExcelWriter(filename)
    for account in simulation.accounts:
        df = account.report.as_df()
        df.to_excel(writer, sheet_name=account.name)
    writer.save() 
Example 26
Project: SniffAir   Author: Tylous   File: export.py    License: MIT License 5 votes vote down vote up
def main(workspace, path, name):
	table_name = ['accessPoints', 'ProbeRequests', 'ProbeRequests', 'EAP', 'Hidden_SSID', 'inscope_accessPoints', 'inscope_ProbeRequests', 'inscope_ProbeResponses']
	sheet_name = ['AccessPoints', 'ProbeRequests', 'ProbeRequests', 'EAP', 'Hidden_SSID', 'Inscope_AccessPoints', 'Inscope_ProbeRequests', 'Inscope_ProbeResponses']
	ws = workspace
	q = queries()
	ws1 = q.db_connect(ws)
	writer = dp.ExcelWriter(path+name+'.xlsx', engine='xlsxwriter')
	j = 0
	print "Exporting: "+path+name+'.xlsx'
	for tbn in table_name:
		try:
			td = dp.read_sql('select * from '+tbn+'', ws1)
			if td.empty:
				pass
				j +=1
				print colors.RD + "[-]" + colors.NRM + " Skipping: " + sheet_name[j] + ". No Data in table."
			else:
				td.to_excel(writer, sheet_name=''+sheet_name[j]+'', index=False)
				j +=1
				print colors.GRN + "[+]" + colors.NRM + " Exporting: " + sheet_name[j] + "."
		except ValueError:
			continue
		except pandas.io.sql.DatabaseError:
			continue
	writer.save()
	print "Export Completed" 
Example 27
Project: tridesclous   Author: tridesclous   File: export.py    License: MIT License 5 votes vote down vote up
def write_out_data(self, out_data, filename):
        assert HAS_PANDAS
        writer = pd.ExcelWriter(filename+'.xlsx')
        for key, (spike_indexes, spike_labels) in out_data.items():
            df = pd.DataFrame()
            df['index'] = spike_indexes
            df['label'] = spike_labels
            df.to_excel(writer, sheet_name=key, index=False)
        writer.save() 
Example 28
Project: airbnb-data-collection   Author: tomslee   File: export_spreadsheet.py    License: MIT License 5 votes vote down vote up
def export_city_summary(ab_config, city, project, start_date):
    logging.info(" ---- Exporting summary spreadsheet" +
                 " for " + city +
                 " using project " + project)
    city_bar = city.replace(" ", "_").lower()
    today = dt.date.today().isoformat()
    xlsxfile = ("./{project}/slee_{project}_{city_bar}_summary_{today}.xlsx"
                ).format(project=project, city_bar=city_bar, today=today)
    writer = pd.ExcelWriter(xlsxfile, engine="xlsxwriter")
    df = survey_df(ab_config, city, start_date)
    city_view = city_view_name(ab_config, city)
    logging.info("Total listings...")
    df = total_listings(ab_config, city_view)
    df.to_excel(writer, sheet_name="Total Listings", index=False)
    logging.info("Listings by room type...")
    df = by_room_type(ab_config, city_view)
    df["Listings"].to_excel(writer,
                            sheet_name="Listings by room type", index=True)
    df["Reviews"].to_excel(writer,
                           sheet_name="Reviews by room type", index=True)
    logging.info("Listings by host type...")
    df = by_host_type(ab_config, city_view)
    df["Hosts"].to_excel(writer,
                         sheet_name="Hosts by host type", index=True)
    df["Listings"].to_excel(writer,
                            sheet_name="Listings by host type", index=True)
    df["Reviews"].to_excel(writer,
                           sheet_name="Reviews by host type", index=True)
    logging.info("Listings by neighborhood...")
    df = by_neighborhood(ab_config, city_view)
    df["Listings"].to_excel(writer,
                            sheet_name="Listings by Neighborhood", index=True)
    df["Reviews"].to_excel(writer,
                           sheet_name="Reviews by Neighborhood", index=True)
    logging.info("Saving " + xlsxfile)
    writer.save() 
Example 29
Project: MOTDT   Author: longcw   File: evaluation.py    License: MIT License 5 votes vote down vote up
def save_summary(summary, filename):
        import pandas as pd
        writer = pd.ExcelWriter(filename)
        summary.to_excel(writer)
        writer.save() 
Example 30
Project: CityEnergyAnalyst   Author: architecture-building-systems   File: inputs.py    License: MIT License 5 votes vote down vote up
def database_dict_to_file(db_dict, db_path):
    with pandas.ExcelWriter(db_path) as writer:
        for sheet_name, data in db_dict.items():
            df = pandas.DataFrame(data).dropna(axis=0, how='all')
            df.to_excel(writer, sheet_name=sheet_name, index=False)
    print('Database file written to {}'.format(db_path))