gL iLddlmZddlmZmZmZmZddlZddlm Z ddl m Z ddl Z ddl mZddlmZmZmZmZmZmZmZmZmZmZddlZddlZddlmZdd lmZdd l m!Z!dd l"m#Z#m$Z$dd l%m&Z&dd l'm(Z(m)Z)ddl*m+Z+ddl,m-Z-ddl.m/Z/m0Z0m1Z1m2Z2ddl3m4Z4ddl5m6Z6ddl7m8Z8ddl9m:Z:m;Z;mm?Z?m@Z@mAZAmBZBmCZCddlDmEZEddlFmGZGerddlHmIZIddlJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTdedjeVe!ddzdzZWe d5d d d d d d d d d d d d d d d d d d d d d d d d d! d6d#ZXed d d d d d d d d d d d d d d d d d d d d d d d d! d7d$ZXe)e6d"%e(eW d8ddddddddddddd&d&d'd'ejddd(dddejdd) d9d*ZXed+ZZGd,d-eeZZ[e)e6d"%Gd.d/eeZZ\d0Z]d1Z^e_e`eae]e^fzZbe)e6d"% d: d;d2ZcGd3d4Zdy)<) annotations)HashableIterableMappingSequenceN)partial)BytesIO)fill) IO TYPE_CHECKINGAnyCallableGenericLiteralTypeVarUnioncastoverload)config)lib) STR_NA_VALUES) get_versionimport_optional_dependency)EmptyDataError)Appenderdoc)find_stack_level)check_dtype_backend)is_boolis_float is_integer is_list_like) DataFrame) _shared_docs)Version) IOHandles get_handlestringify_pathvalidate_header_arg)fill_mi_headerget_default_engine get_writermaybe_convert_usecolspop_header_name) TextParser)validate_integer) TracebackType) DtypeArg DtypeBackendExcelWriterIfSheetExistsFilePathIntStrT ReadBufferSelfSequenceNotStrStorageOptionsWriteExcelBuffera Read an Excel file into a ``pandas`` ``DataFrame``. Supports `xls`, `xlsx`, `xlsm`, `xlsb`, `odf`, `ods` and `odt` file extensions read from a local filesystem or URL. Supports an option to read a single sheet or a list of sheets. Parameters ---------- io : str, bytes, ExcelFile, xlrd.Book, path object, or file-like object Any valid string path is acceptable. The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. A local file could be: ``file://localhost/path/to/table.xlsx``. If you want to pass in a path object, pandas accepts any ``os.PathLike``. By file-like object, we refer to objects with a ``read()`` method, such as a file handle (e.g. via builtin ``open`` function) or ``StringIO``. .. deprecated:: 2.1.0 Passing byte strings is deprecated. To read from a byte string, wrap it in a ``BytesIO`` object. sheet_name : str, int, list, or None, default 0 Strings are used for sheet names. Integers are used in zero-indexed sheet positions (chart sheets do not count as a sheet position). Lists of strings/integers are used to request multiple sheets. Specify ``None`` to get all worksheets. Available cases: * Defaults to ``0``: 1st sheet as a `DataFrame` * ``1``: 2nd sheet as a `DataFrame` * ``"Sheet1"``: Load sheet with name "Sheet1" * ``[0, 1, "Sheet5"]``: Load first, second and sheet named "Sheet5" as a dict of `DataFrame` * ``None``: All worksheets. header : int, list of int, default 0 Row (0-indexed) to use for the column labels of the parsed DataFrame. If a list of integers is passed those row positions will be combined into a ``MultiIndex``. Use None if there is no header. names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None. index_col : int, str, list of int, default None Column (0-indexed) to use as the row labels of the DataFrame. Pass None if there is no such column. If a list is passed, those columns will be combined into a ``MultiIndex``. If a subset of data is selected with ``usecols``, index_col is based on the subset. Missing values will be forward filled to allow roundtripping with ``to_excel`` for ``merged_cells=True``. To avoid forward filling the missing values use ``set_index`` after reading the data instead of ``index_col``. usecols : str, list-like, or callable, default None * If None, then parse all columns. * If str, then indicates comma separated list of Excel column letters and column ranges (e.g. "A:E" or "A,C,E:F"). Ranges are inclusive of both sides. * If list of int, then indicates list of column numbers to be parsed (0-indexed). * If list of string, then indicates list of column names to be parsed. * If callable, then evaluate each column name against it and parse the column if the callable returns ``True``. Returns a subset of the columns according to behavior above. dtype : Type name or dict of column -> type, default None Data type for data or columns. E.g. {{'a': np.float64, 'b': np.int32}} Use ``object`` to preserve data as stored in Excel and not interpret dtype, which will necessarily result in ``object`` dtype. If converters are specified, they will be applied INSTEAD of dtype conversion. If you use ``None``, it will infer the dtype of each column based on the data. engine : {{'openpyxl', 'calamine', 'odf', 'pyxlsb', 'xlrd'}}, default None If io is not a buffer or path, this must be set to identify io. Engine compatibility : - ``openpyxl`` supports newer Excel file formats. - ``calamine`` supports Excel (.xls, .xlsx, .xlsm, .xlsb) and OpenDocument (.ods) file formats. - ``odf`` supports OpenDocument file formats (.odf, .ods, .odt). - ``pyxlsb`` supports Binary Excel files. - ``xlrd`` supports old-style Excel files (.xls). When ``engine=None``, the following logic will be used to determine the engine: - If ``path_or_buffer`` is an OpenDocument format (.odf, .ods, .odt), then `odf `_ will be used. - Otherwise if ``path_or_buffer`` is an xls format, ``xlrd`` will be used. - Otherwise if ``path_or_buffer`` is in xlsb format, ``pyxlsb`` will be used. - Otherwise ``openpyxl`` will be used. converters : dict, default None Dict of functions for converting values in certain columns. Keys can either be integers or column labels, values are functions that take one input argument, the Excel cell content, and return the transformed content. true_values : list, default None Values to consider as True. false_values : list, default None Values to consider as False. skiprows : list-like, int, or callable, optional Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file. If callable, the callable function will be evaluated against the row indices, returning True if the row should be skipped and False otherwise. An example of a valid callable argument would be ``lambda x: x in [0, 2]``. nrows : int, default None Number of rows to parse. na_values : scalar, str, list-like, or dict, default None Additional strings to recognize as NA/NaN. If dict passed, specific per-column NA values. By default the following values are interpreted as NaN: 'z', 'Fz )subsequent_indenta_'. keep_default_na : bool, default True Whether or not to include the default NaN values when parsing the data. Depending on whether ``na_values`` is passed in, the behavior is as follows: * If ``keep_default_na`` is True, and ``na_values`` are specified, ``na_values`` is appended to the default NaN values used for parsing. * If ``keep_default_na`` is True, and ``na_values`` are not specified, only the default NaN values are used for parsing. * If ``keep_default_na`` is False, and ``na_values`` are specified, only the NaN values specified ``na_values`` are used for parsing. * If ``keep_default_na`` is False, and ``na_values`` are not specified, no strings will be parsed as NaN. Note that if `na_filter` is passed in as False, the ``keep_default_na`` and ``na_values`` parameters will be ignored. na_filter : bool, default True Detect missing value markers (empty strings and the value of na_values). In data without any NAs, passing ``na_filter=False`` can improve the performance of reading a large file. verbose : bool, default False Indicate number of NA values placed in non-numeric columns. parse_dates : bool, list-like, or dict, default False The behavior is as follows: * ``bool``. If True -> try parsing the index. * ``list`` of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column. * ``list`` of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column. * ``dict``, e.g. {{'foo' : [1, 3]}} -> parse columns 1, 3 as date and call result 'foo' If a column or index contains an unparsable date, the entire column or index will be returned unaltered as an object data type. If you don`t want to parse some cells as date just change their type in Excel to "Text". For non-standard datetime parsing, use ``pd.to_datetime`` after ``pd.read_excel``. Note: A fast-path exists for iso8601-formatted dates. date_parser : function, optional Function to use for converting a sequence of string columns to an array of datetime instances. The default uses ``dateutil.parser.parser`` to do the conversion. Pandas will try to call `date_parser` in three different ways, advancing to the next if an exception occurs: 1) Pass one or more arrays (as defined by `parse_dates`) as arguments; 2) concatenate (row-wise) the string values from the columns defined by `parse_dates` into a single array and pass that; and 3) call `date_parser` once for each row using one or more strings (corresponding to the columns defined by `parse_dates`) as arguments. .. deprecated:: 2.0.0 Use ``date_format`` instead, or read in as ``object`` and then apply :func:`to_datetime` as-needed. date_format : str or dict of column -> format, default ``None`` If used in conjunction with ``parse_dates``, will parse dates according to this format. For anything more complex, please read in as ``object`` and then apply :func:`to_datetime` as-needed. .. versionadded:: 2.0.0 thousands : str, default None Thousands separator for parsing string columns to numeric. Note that this parameter is only necessary for columns stored as TEXT in Excel, any numeric columns will automatically be parsed, regardless of display format. decimal : str, default '.' Character to recognize as decimal point for parsing string columns to numeric. Note that this parameter is only necessary for columns stored as TEXT in Excel, any numeric columns will automatically be parsed, regardless of display format.(e.g. use ',' for European data). .. versionadded:: 1.4.0 comment : str, default None Comments out remainder of line. Pass a character or characters to this argument to indicate comments in the input file. Any data between the comment string and the end of the current line is ignored. skipfooter : int, default 0 Rows at the end to skip (0-indexed). {storage_options} dtype_backend : {{'numpy_nullable', 'pyarrow'}}, default 'numpy_nullable' Back-end data type applied to the resultant :class:`DataFrame` (still experimental). Behaviour is as follows: * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame` (default). * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype` DataFrame. .. versionadded:: 2.0 engine_kwargs : dict, optional Arbitrary keyword arguments passed to excel engine. Returns ------- DataFrame or dict of DataFrames DataFrame from the passed in Excel file. See notes in sheet_name argument for more information on when a dict of DataFrames is returned. See Also -------- DataFrame.to_excel : Write DataFrame to an Excel file. DataFrame.to_csv : Write DataFrame to a comma-separated values (csv) file. read_csv : Read a comma-separated values (csv) file into DataFrame. read_fwf : Read a table of fixed-width formatted lines into DataFrame. Notes ----- For specific information on the methods used for each Excel engine, refer to the pandas :ref:`user guide ` Examples -------- The file can be read using the file name as string or an open file object: >>> pd.read_excel('tmp.xlsx', index_col=0) # doctest: +SKIP Name Value 0 string1 1 1 string2 2 2 #Comment 3 >>> pd.read_excel(open('tmp.xlsx', 'rb'), ... sheet_name='Sheet3') # doctest: +SKIP Unnamed: 0 Name Value 0 0 string1 1 1 1 string2 2 2 2 #Comment 3 Index and header can be specified via the `index_col` and `header` arguments >>> pd.read_excel('tmp.xlsx', index_col=None, header=None) # doctest: +SKIP 0 1 2 0 NaN Name Value 1 0.0 string1 1 2 1.0 string2 2 3 2.0 #Comment 3 Column types are inferred but can be explicitly specified >>> pd.read_excel('tmp.xlsx', index_col=0, ... dtype={{'Name': str, 'Value': float}}) # doctest: +SKIP Name Value 0 string1 1.0 1 string2 2.0 2 #Comment 3.0 True, False, and NA values, and thousands separators have defaults, but can be explicitly specified, too. Supply the values you would like as strings or lists of strings! >>> pd.read_excel('tmp.xlsx', index_col=0, ... na_values=['string1', 'string2']) # doctest: +SKIP Name Value 0 NaN 1 1 NaN 2 2 #Comment 3 Comment lines in the excel input file can be skipped using the ``comment`` kwarg. >>> pd.read_excel('tmp.xlsx', index_col=0, comment='#') # doctest: +SKIP Name Value 0 string1 1.0 1 string2 2.0 2 None NaN .)headernames index_colusecolsdtypeengine converters true_values false_valuesskiprowsnrows na_valueskeep_default_na na_filterverbose parse_dates date_parser date_format thousandsdecimalcomment skipfooterstorage_options dtype_backendrTcyNio sheet_namer>r?r@rArBrCrDrErFrGrHrIrJrKrLrMrNrOrPrQrRrSrTrUs [/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/pandas/io/excel/_base.py read_excelr]uHcyrWrXrYs r\r]r]r^r_)rTTF.)r>r?r@rArBrCrDrErFrGrHrIrJrKrLrMrNrOrPrQrRrSrTrU engine_kwargscJt|d}|i}t|tsd}t||||}n|r||jk7r t d |j |||||||| | | | | |||||||||||}|r|j |S#|r|j wwxYw)NFT)rTrCrbz_Engine should not be specified when passing an ExcelFile - ExcelFile already has the engine set)r[r>r?r@rArBrDrErFrGrHrIrJrKrLrMrNrOrPrQrRrSrU)r isinstance ExcelFilerC ValueErrorparseclose)rZr[r>r?r@rArBrCrDrErFrGrHrIrJrKrLrMrNrOrPrQrRrSrTrUrb should_closedatas r\r]r]sJ &L b) $  +'   Fbii' B  xx!!#%+###!'/ 6  HHJ K  HHJ s (B B" _WorkbookTc^eZdZUded< d ddZeddZddZddZeddZ dd Z dd Z ddd Z dd Z dd Z d dZ d!dZdddddddddddddej$dddddej$f d"dZy)#BaseExcelReaderrkbookNc|i}t|tr t|}t|ddi|_t|t |j fst|d|d|_t|jj|j r|jj|_ yt|jjdrR|jjjd |j|jj||_ ytd#t$r|jwxYw) Nmethod)handle compressionrbFrTis_textreadrzCMust explicitly set engine if not passing in buffer or path for io.)rdbytesr r&handlesre_workbook_classr'rqrnhasattrseek load_workbook Exceptionrhrf)selffilepath_or_bufferrTrbs r\__init__zBaseExcelReader.__init__"s  M (% 0!();!<  %Hd3C  ,y$:N:N.OP%"D/SXDL dll))4+?+? @ ++DI T\\((& 1 LL   $ $Q '  ..t||/B/BMR U     s 0+D''EctrWNotImplementedErrorr~s r\ryzBaseExcelReader._workbook_classF!!r_ctrWr)r~rrbs r\r|zBaseExcelReader.load_workbookJ!!r_ct|drat|jdr|jjn0t|jdr|jj|jjy)Nrnrhrelease_resources)rzrnrhrrxrs r\rhzBaseExcelReader.closeMs[ 4 tyy'* !$78 ++- r_ctrWrrs r\ sheet_nameszBaseExcelReader.sheet_namesZrr_ctrWrr~names r\get_sheet_by_namez!BaseExcelReader.get_sheet_by_name^rr_ctrWr)r~indexs r\get_sheet_by_indexz"BaseExcelReader.get_sheet_by_indexarr_ctrWr)r~sheetrowss r\get_sheet_datazBaseExcelReader.get_sheet_datadrr_c\t|j}||k\rtd|d|dy)NzWorksheet index z is invalid, z worksheets found)lenrrf)r~rn_sheetss r\raise_if_bad_sheet_by_indexz+BaseExcelReader.raise_if_bad_sheet_by_indexgs?t''( H "5'xj@QR  r_c>||jvrtd|dy)NzWorksheet named 'z ' not found)rrfrs r\raise_if_bad_sheet_by_namez*BaseExcelReader.raise_if_bad_sheet_by_namens* t'' '0kBC C (r_cHd}d}||kr||s|dz }|dz }||kr|S)a Determine how many file rows are required to obtain `nrows` data rows when `skiprows` is a function. Parameters ---------- skiprows : function The function passed to read_excel by the user. rows_to_use : int The number of rows that will be needed for the header and the data. Returns ------- int rrX)r~rG rows_to_useirows_used_so_fars r\_check_skiprows_funcz$BaseExcelReader._check_skiprows_funcrsC* ,A; A% FA,r_c|y|d}n9t|rtt|}d|z}ntt|}d|dz}t |r%|#tt|}t |dkDr|dz }|||zSt|rtt|}||z|zSt |r3dd}tt|}|j t||||zSt|r|j |||zSy)a If nrows specified, find the number of rows needed from the file, otherwise return None. Parameters ---------- header : int, list of int, or None See read_excel docstring. index_col : int, str, list of int, or None See read_excel docstring. skiprows : list-like, int, callable, or None See read_excel docstring. nrows : int or None See read_excel docstring. Returns ------- int or None Nrc ||vSrWrX)rGxs r\fz%BaseExcelReader._calc_rows..fs H}$r_)rGrrintreturnbool) r!rrrr"rrrcallable)r~r>r@rGrH header_rowsrs r\ _calc_rowszBaseExcelReader._calc_rowss6 = >K  #v&Ff*K(F+FfRj.K  I$9(F+F6{Qq  & & h C*H&1 1  ! %Hh/H,,WQ-A;QVCVW W H ,,e#  r_rFrac h t|td| d}t|tr|}d}n(||j}d}nt|t r|g}n|g}t ttttt fttj|j}i}d}|D]}|}| rtd|t|t r|j|}n|j|}|j||| | }|j!||}t#|dr|j%t'|}|st)||<d}d}t+|r$t|t,sJd}t/|dk(rd}|rt t,t|d}d} |t+|rt|t,sJg} dgt/|dz}!|D]}"t1| rt| tsJ|"| z }"|"t/|dz kDrt3d|"d t/|dz d t5||"|!\||"<}!|lt7||"|\}#}$| j9|#d}%|r|s|t|tr|g}&nt|t,sJ|}&t|t,sJt/|t/|krF|t/|}'t;|'D()cgc]\}(})!|(s|(|&vr|)}*}(})t=d |*D}%t+|r|d}+n$t|trd|z}+ndt?|z}+|%r|+dz }+|+t/|krbt|t,sJ|D]K},||+|,}-tA|+dzt/|D]&}"||"|,d k(s||"|, |-||"|,<||"|,}-(M tC|fid |d|d|d|%d|d|d|d| d| d| ddd| d|d|d|d|d|d|d|d||}.|.jE| ||<| r&||jFjI| ||_#| t3d#|r|S||Scc})}(w#tJ$rt)||<YtL$r2}/|/jNdd!|d"g|/jNdd|/_'|/d}/~/wwxYw)$NrHFTzReading sheet rhrrz header index z exceeds maximum index z of data.c32K|]}|dk(xs|duyw)NrX).0rs r\ z(BaseExcelReader.parse..Ms )W1!r'*>Q$Y*>)Wsrr?r>r@has_index_namesrBrErFrGrIskip_blank_linesrMrNrOrPrQrRrSrArU)rHz (sheet: )zSheet name is an empty list)(r)r0rdlistrstrrrrdictfromkeyskeysprintrrrrrzrhr-r#r"rrr!rfr*r.append enumerateallmaxranger/rvcolumns set_namesrr}args)0r~r[r>r?r@rArBrErFrGrHrIrLrMrNrOrPrQrRrSrUkwdsret_dictsheetsoutputlast_sheetname asheetnamerfile_rows_neededrjis_list_headeris_len_one_list_header header_names control_rowrow header_name_rindex_col_listpotential_index_namesrrpotential_dataoffsetcollastparsererrs0 r\rgzBaseExcelReader.parses0 F#%( j$ 'FH  %%FH  C ( \F \FeDItCy014 f8M8R8R8T3UV U J'Nzl34*c*..z:// ;#vy(ER &&u.>?Dug& +G4G%.[z""N%* "F#!&(333!%v;!#-1*%hsmV4Q7 L!l6&:!&(333! #fs47|3 !9C!(+)(C888xSY]*(+C50G"4y1}oY8 .2I&N& '*)W)W&WOI&>F,ZFV_F #aKFCI%%i:::(6#F|C0#(!SY#?6C#Cy~3tCy~7M15S #'+Cy~ 66' #"(  %4   !,".& (&+!,!,!, (!"$#$$%& *'($)*#0-2&,[[u[%=z"17 1C1K1K1U1U$2F:&.WU n  !:; ; M.) )i&L" 1%.[z" "xx{m9ZLBRSXXab\R  s%$Q:BQR17R1?-R,,R1)NN)rTStorageOptions | Nonerb dict | NonerNone)rztype[_WorkbookT]rrkrr)rz list[str])rr)rrrW)r int | None)rrrr)rrrr)rGrrrrr) r>int | Sequence[int] | Noner@rrG4Sequence[int] | int | Callable[[int], object] | NonerHrrr)$r[(str | int | list[int] | list[str] | Noner>rr?'SequenceNotStr[Hashable] | range | Noner@rrBDtypeArg | NonerEIterable[Hashable] | NonerFrrGrrHrrLrrMlist | dict | boolrNCallable | lib.NoDefaultrO dict[Hashable, str] | str | NonerP str | NonerQrrRrrSrrUDtypeBackend | lib.NoDefault)__name__ __module__ __qualname____annotations__rpropertyryr|rhrrrrrrrrr no_defaultrgrXr_r\rmrms  26%) "/"# "  "H""" """""D :>*>.>G >  >  >D@A-.9=04!%1526IM */038< $"69nn+M*<M*+M*7 M* . M*M*/M*0M*GM*M*M*(M*.M* 6!M*"#M*$%M*&'M*()M**4+M*r_rmceZdZUdZded<ded< d ddZdZeddZedd Z edd Z edd Z d d d Z d!d Z d d"dZeddZeddZeddZddZd#dZ d$dZed%dZd&dZ d'dZd!dZy)( ExcelWritera Class for writing DataFrame objects into excel sheets. Default is to use: * `xlsxwriter `__ for xlsx files if xlsxwriter is installed otherwise `openpyxl `__ * `odswriter `__ for ods files See ``DataFrame.to_excel`` for typical usage. The writer should be used as a context manager. Otherwise, call `close()` to save and close any opened file handles. Parameters ---------- path : str or typing.BinaryIO Path to xls or xlsx or ods file. engine : str (optional) Engine to use for writing. If None, defaults to ``io.excel..writer``. NOTE: can only be passed as a keyword argument. date_format : str, default None Format string for dates written into Excel files (e.g. 'YYYY-MM-DD'). datetime_format : str, default None Format string for datetime objects written into Excel files. (e.g. 'YYYY-MM-DD HH:MM:SS'). mode : {{'w', 'a'}}, default 'w' File mode to use (write or append). Append does not work with fsspec URLs. {storage_options} if_sheet_exists : {{'error', 'new', 'replace', 'overlay'}}, default 'error' How to behave when trying to write to a sheet that already exists (append mode only). * error: raise a ValueError. * new: Create a new sheet, with a name determined by the engine. * replace: Delete the contents of the sheet before writing to it. * overlay: Write contents to the existing sheet without first removing, but possibly over top of, the existing contents. .. versionadded:: 1.3.0 .. versionchanged:: 1.4.0 Added ``overlay`` option engine_kwargs : dict, optional Keyword arguments to be passed into the engine. These will be passed to the following functions of the respective engines: * xlsxwriter: ``xlsxwriter.Workbook(file, **engine_kwargs)`` * openpyxl (write mode): ``openpyxl.Workbook(**engine_kwargs)`` * openpyxl (append mode): ``openpyxl.load_workbook(file, **engine_kwargs)`` * odswriter: ``odf.opendocument.OpenDocumentSpreadsheet(**engine_kwargs)`` .. versionadded:: 1.3.0 Notes ----- For compatibility with CSV writers, ExcelWriter serializes lists and dicts to strings before writing. Examples -------- Default usage: >>> df = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"]) # doctest: +SKIP >>> with pd.ExcelWriter("path_to_file.xlsx") as writer: ... df.to_excel(writer) # doctest: +SKIP To write to separate sheets in a single file: >>> df1 = pd.DataFrame([["AAA", "BBB"]], columns=["Spam", "Egg"]) # doctest: +SKIP >>> df2 = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"]) # doctest: +SKIP >>> with pd.ExcelWriter("path_to_file.xlsx") as writer: ... df1.to_excel(writer, sheet_name="Sheet1") # doctest: +SKIP ... df2.to_excel(writer, sheet_name="Sheet2") # doctest: +SKIP You can set the date format or datetime format: >>> from datetime import date, datetime # doctest: +SKIP >>> df = pd.DataFrame( ... [ ... [date(2014, 1, 31), date(1999, 9, 24)], ... [datetime(1998, 5, 26, 23, 33, 4), datetime(2014, 2, 28, 13, 5, 13)], ... ], ... index=["Date", "Datetime"], ... columns=["X", "Y"], ... ) # doctest: +SKIP >>> with pd.ExcelWriter( ... "path_to_file.xlsx", ... date_format="YYYY-MM-DD", ... datetime_format="YYYY-MM-DD HH:MM:SS" ... ) as writer: ... df.to_excel(writer) # doctest: +SKIP You can also append to an existing Excel file: >>> with pd.ExcelWriter("path_to_file.xlsx", mode="a", engine="openpyxl") as writer: ... df.to_excel(writer, sheet_name="Sheet3") # doctest: +SKIP Here, the `if_sheet_exists` parameter can be set to replace a sheet if it already exists: >>> with ExcelWriter( ... "path_to_file.xlsx", ... mode="a", ... engine="openpyxl", ... if_sheet_exists="replace", ... ) as writer: ... df.to_excel(writer, sheet_name="Sheet1") # doctest: +SKIP You can also write multiple DataFrames to a single sheet. Note that the ``if_sheet_exists`` parameter needs to be set to ``overlay``: >>> with ExcelWriter("path_to_file.xlsx", ... mode="a", ... engine="openpyxl", ... if_sheet_exists="overlay", ... ) as writer: ... df1.to_excel(writer, sheet_name="Sheet1") ... df2.to_excel(writer, sheet_name="Sheet1", startcol=3) # doctest: +SKIP You can store Excel file in RAM: >>> import io >>> df = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"]) >>> buffer = io.BytesIO() >>> with pd.ExcelWriter(buffer) as writer: ... df.to_excel(writer) You can pack Excel file into zip archive: >>> import zipfile # doctest: +SKIP >>> df = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"]) # doctest: +SKIP >>> with zipfile.ZipFile("path_to_file.zip", "w") as zf: ... with zf.open("filename.xlsx", "w") as buffer: ... with pd.ExcelWriter(buffer) as writer: ... df.to_excel(writer) # doctest: +SKIP You can specify additional arguments to the underlying engine: >>> with pd.ExcelWriter( ... "path_to_file.xlsx", ... engine="xlsxwriter", ... engine_kwargs={{"options": {{"nan_inf_to_errors": True}}}} ... ) as writer: ... df.to_excel(writer) # doctest: +SKIP In append mode, ``engine_kwargs`` are passed through to openpyxl's ``load_workbook``: >>> with pd.ExcelWriter( ... "path_to_file.xlsx", ... engine="openpyxl", ... mode="a", ... engine_kwargs={{"keep_vba": True}} ... ) as writer: ... df.to_excel(writer, sheet_name="Sheet2") # doctest: +SKIP r_enginetuple[str, ...]_supported_extensionsNc |tur|t|trk|dk(rft|tr&tjj |ddd} nd} t jd| dd}|dk(r t| d }|Jt|}tj|S#t$r} td | d | d} ~ wwxYw) Nautorrxlsx io.excel.z.writerTsilentwritermodezNo engine for filetype: '')rrdrospathsplitextr get_optionr+KeyErrorrfr,object__new__) clsrrCrOdatetime_formatrrTif_sheet_existsrbextrs r\rzExcelWriter.__new__\s + ~*VS"9f>NdC(''**404QR8C CR#..3%w/GPTUF'!3Ch!G % %%V$C~~c"" R$'@Q%GHcQRs-B** C3CCc|jS)z'Extensions that writer engine supports.)rrs r\supported_extensionsz ExcelWriter.supported_extensionss)))r_c|jS)zName of engine.)rrs r\rCzExcelWriter.engines||r_ct)z(Mapping of sheet names to sheet objects.rrs r\rzExcelWriter.sheetss "!r_ct)z Book instance. Class type will depend on the engine used. This attribute can be used to access engine-specific features. rrs r\rnzExcelWriter.books "!r_ct)a Write given formatted cells into Excel an excel sheet Parameters ---------- cells : generator cell of formatted data to save to Excel sheet sheet_name : str, default None Name of Excel sheet, if None, then use self.cur_sheet startrow : upper left cell row to dump data frame startcol : upper left cell column to dump data frame freeze_panes: int tuple of length 2 contains the bottom-most row and right-most column to freeze r)r~cellsr[startrowstartcol freeze_paness r\ _write_cellszExcelWriter._write_cellss ,"!r_ct)z( Save workbook to disk. rrs r\_savezExcelWriter._saves "!r_c &t|tr3tjj |d} |j | d|vr|dz }|j dd}|dvrtd|d|rd|vr td|d }||_tttt|d di |_ t|tst|||d |_ d|_|d|_n||_|d|_||_y||_||_y)Nrbazr+)Nerrornewreplaceoverlayrz^' is not valid for if_sheet_exists. Valid options are 'error', 'new', 'replace' and 'overlay'.z7if_sheet_exists is only valid in append mode (mode='a')rrr)rrFrtz YYYY-MM-DDzYYYY-MM-DD HH:MM:SS)rdrrrrcheck_extensionrrf_if_sheet_existsr&rr rw_handlesrr' _cur_sheet _date_format_datetime_format_mode) r~rrCrOrrrTr rbr s r\rzExcelWriter.__init__s9 dC ''""4(,C   % d? CKD||C& "N NO$%MM  t4/VW W  "%O /" ED ! t/D  $ ,&dOUDM   ,D  +D   "$9D ! %4D ! r_c|jSzW Format string for dates written into Excel files (e.g. 'YYYY-MM-DD'). )r#rs r\rOzExcelWriter.date_formats    r_c|jSr')r$rs r\rzExcelWriter.datetime_format $$$r_c|jS)z[ How to behave when writing to a sheet that already exists in append mode. )r rs r\r zExcelWriter.if_sheet_existsr)r_cDt|jjddS)Nrr)getattrr!rqrs r\ __fspath__zExcelWriter.__fspath__st}}++VR88r_c<| |j}| td|S)Nz8Must pass explicit sheet_name or set _cur_sheet property)r"rf)r~r[s r\_get_sheet_namezExcelWriter._get_sheet_names)  J  WX Xr_cd}t|rt|}||fSt|rt|}||fSt |rt |}||fSt |tjr|j}||fSt |tjr|j}||fSt |tjr|jdz }d}||fSt|}||fS)aG Convert numpy types to Python types for the Excel writers. Parameters ---------- val : object Value to be written into cells Returns ------- Tuple with the first element being the converted value and the second being an optional format NiQ0)r!rr floatrrrddatetimer$dater# timedelta total_secondsr)r~valfmts r\_value_with_fmtzExcelWriter._value_with_fmt s$ c?c(CCxc]*CCxS\s)CCxX.. /''CCxX]] +##CCx X// 0##%-CCCxc(CCxr_cjdrddtfd|jDstd|jddy) z checks that path's extension against the Writer's supported extensions. If it isn't supported, raises UnsupportedFiletypeError. rarNc3&K|]}|v ywrWrX)r extensionr s r\rz.ExcelWriter.check_extension..;sO 3)#OszInvalid extension for engine 'z': 'rT) startswithanyrrfrC)rr s `r\rzExcelWriter.check_extension3sS >># ab'COS5N5NOO=cjj\cURSTU Ur_c|SrWrXrs r\ __enter__zExcelWriter.__enter__@ r_c$|jyrWrhr~exc_type exc_value tracebacks r\__exit__zExcelWriter.__exit__C r_cX|j|jjy)z+synonym for save, to make it more file-likeN)rr!rhrs r\rhzExcelWriter.closeKs  r_)NNNwNNN)r)FilePath | WriteExcelBuffer | ExcelWriterrCrrOrrrrrrTrr ExcelWriterIfSheetExists | Nonerbrrr8)rr)rr)rzdict[str, Any]r)NrrN) r[rrrrrrztuple[int, int] | Nonerrr)rrLrCrrOrrrrrrTrr rMrbzdict[str, Any] | Nonerr)r[rrr)rzOtuple[int | float | bool | str | datetime.datetime | datetime.date, str | None])r rrz Literal[True]rr8rEztype[BaseException] | NonerFzBaseException | NonerGzTracebackType | Nonerr)rrr__doc__rr_pathrr rCrrnrrrrOrr r-r/r9 classmethodrr@rHrhrXr_r\rrs>`pL** ""&&*15;?%) #7 # # # $ #  #/ #9 ## #  #F E **"""""&/3 "" "  " - " "0"""&&*15;?/35755 5 $ 5  5/595-5 5n!! %% %% 9$ $L  ,((   r_r)s s s sࡱsPKc t|tr t|}t|d|d5}|j}|j d|j t}| tdt|tsJ||j dtfdtDr dddyjts dddytj|5}|jDcgc]"}|j!d d j#$}}dddd vr dddy d |vr dddyd|vr dddy dddycc}w#1swYBxYw#1swYyxYw)a8 Inspect the path or content of an excel file and get its format. Adopted from xlrd: https://github.com/python-excel/xlrd. Parameters ---------- content_or_path : str or file-like object Path to file or content of file to inspect. May be a URL. {storage_options} Returns ------- str or None Format of file if it can be determined. Raises ------ ValueError If resulting stream is empty. BadZipFile If resulting stream does not have an XLS signature and is not a valid zipfile. rsFrtrNzstream is emptyc3@K|]}j|ywrW)r=)rsigpeeks r\rz'inspect_excel_format..s>ts#>sxls\/zxl/workbook.xmlrzxl/workbook.binxlsbz content.xmlodszip)rdrwr r'rqr{rv PEEK_SIZErfr>XLS_SIGNATURESr= ZIP_SIGNATUREzipfileZipFilenamelistrlower) content_or_pathrTrqstreambufzfrcomponent_namesrVs @r\inspect_excel_formatri[sz8/5)!/2    Akk)$ ;./ /#u%%% A >~> >/"__V $ =?KKM48 T3'--/O   /34  /78 O +;<=(  #sTA>E03E0E0'E$:'E!E$# E09E0E0E0E$$E- )E00E9cheZdZUdZddlmZddlmZddlm Z ddl m Z ddl m Z e e ee edZd ed < d dd Zd Zddd d d d d d d d d dej&d d d dej&f ddZedZedZddZddZ ddZy )reai Class for parsing tabular Excel sheets into DataFrame objects. See read_excel for more documentation. Parameters ---------- path_or_buffer : str, bytes, path object (pathlib.Path or py._path.local.LocalPath), A file-like object, xlrd workbook or openpyxl workbook. If a string or path object, expected to be a path to a .xls, .xlsx, .xlsb, .xlsm, .odf, .ods, or .odt file. engine : str, default None If io is not a buffer or path, this must be set to identify io. Supported engines: ``xlrd``, ``openpyxl``, ``odf``, ``pyxlsb``, ``calamine`` Engine compatibility : - ``xlrd`` supports old-style Excel files (.xls). - ``openpyxl`` supports newer Excel file formats. - ``odf`` supports OpenDocument file formats (.odf, .ods, .odt). - ``pyxlsb`` supports Binary Excel files. - ``calamine`` supports Excel (.xls, .xlsx, .xlsm, .xlsb) and OpenDocument (.ods) file formats. .. versionchanged:: 1.2.0 The engine `xlrd `_ now only supports old-style ``.xls`` files. When ``engine=None``, the following logic will be used to determine the engine: - If ``path_or_buffer`` is an OpenDocument format (.odf, .ods, .odt), then `odf `_ will be used. - Otherwise if ``path_or_buffer`` is an xls format, ``xlrd`` will be used. - Otherwise if ``path_or_buffer`` is in xlsb format, `pyxlsb `_ will be used. .. versionadded:: 1.3.0 - Otherwise if `openpyxl `_ is installed, then ``openpyxl`` will be used. - Otherwise if ``xlrd >= 2.0`` is installed, a ``ValueError`` will be raised. .. warning:: Please do not report issues when using ``xlrd`` to read ``.xlsx`` files. This is not supported, switch to using ``openpyxl`` instead. engine_kwargs : dict, optional Arbitrary keyword arguments passed to excel engine. Examples -------- >>> file = pd.ExcelFile('myfile.xlsx') # doctest: +SKIP >>> with pd.ExcelFile("myfile.xls") as xls: # doctest: +SKIP ... df1 = pd.read_excel(xls, "Sheet1") # doctest: +SKIP r)CalamineReader) ODFReader)OpenpyxlReader) PyxlsbReader) XlrdReader)xlrdopenpyxlodfpyxlsbcalaminezMapping[str, Any]_enginesNc~|i}|||jvrtd|t|tr/t |}t j dtt||_ t||_ tddd}nddl }tt|}|b|t|j rd}nt#|| }| td t%j&d |d d }|dk(r t)|d}|J||_||_|j||j|||_y)NzUnknown engine: zPassing bytes to 'read_excel' is deprecated and will be removed in a future version. To read from a byte string, wrap it in a `BytesIO` object.) stacklevelrpignore)errorsrrW)rdrTzLExcel file format cannot be determined, you must specify an engine manually.rz.readerTrrreaderr)rTrb)rurfrdrwr warningswarn FutureWarningrrZr(_iorrpr%rBookrirrr+rCrT_reader)r~path_or_bufferrCrTrb xlrd_versionrpr s r\rzExcelFile.__init__sW  M  & "=/x89 9 ne ,$^4N MM>+-  !!.1 &fX > FL ";t#45L >'J~tyy,Q*$2O;$. &&3%w'?MF+Ch?!!! .,t}}V, HH+'  r_c|jSrW)r~rs r\r-zExcelFile.__fspath__%s xxr_Fc |jjdid|d|d|d|d|d|d|d|d | d | d | d | d | d|d|d|d|d||S)aO Parse specified sheet(s) into a DataFrame. Equivalent to read_excel(ExcelFile, ...) See the read_excel docstring for more info on accepted parameters. Returns ------- DataFrame or dict of DataFrames DataFrame from the passed in Excel file. Examples -------- >>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['A', 'B', 'C']) >>> df.to_excel('myfile.xlsx') # doctest: +SKIP >>> file = pd.ExcelFile('myfile.xlsx') # doctest: +SKIP >>> file.parse() # doctest: +SKIP r[r>r?r@rArDrErFrGrHrIrMrNrOrPrRrSrUrX)rrg)r~r[r>r?r@rArDrErFrGrHrIrMrNrOrPrRrSrUrs r\rgzExcelFile.parse(sP"t||!! !       "  $ &     $ $ $   ! ""# $('  r_c.|jjSrW)rrnrs r\rnzExcelFile.bookfs||   r_c.|jjSrW)rrrs r\rzExcelFile.sheet_namesjs||'''r_c8|jjy)zclose io if necessaryN)rrhrs r\rhzExcelFile.closens r_c|SrWrXrs r\r@zExcelFile.__enter__rrAr_c$|jyrWrCrDs r\rHzExcelFile.__exit__urIr_)NNN)rCrrTrrbrrr) r[rr>rr?rr@rrErrFrrGrrHrrMrrNrrOz str | dict[Hashable, str] | NonerPrrRrrSrrUrrz7DataFrame | dict[str, DataFrame] | dict[int, DataFrame]rrNrO)rrrrPpandas.io.excel._calaminerkpandas.io.excel._odfreaderrlpandas.io.excel._openpyxlrmpandas.io.excel._pyxlsbrnpandas.io.excel._xlrdrorurrr-rrrgrrnrrhr@rHrXr_r\reres7r94840"" #H"15%) @ @ / @ # @  @ D @A-.9=041526IM */038< $"69nn'< << +< 7 < . < /< 0< G< < (< .< 6< !< "#< $%< &4'< * A+< |!!((,((   r_re).)2r[z str | intr>rr?rr@ int | str | Sequence[int] | NonerAHint | str | Sequence[int] | Sequence[str] | Callable[[str], bool] | NonerBrrC?Literal['xlrd', 'openpyxl', 'odf', 'pyxlsb', 'calamine'] | NonerD0dict[str, Callable] | dict[int, Callable] | NonerErrFrrGrrHrrJrrKrrLrrMrrNrrOrrPrrQrrRrrSrrTr:rUrrr#)2r[zlist[IntStrT] | Noner>rr?rr@rrArrBrrCrrDrrErrFrrGrrHrrJrrKrrLrrMrrNrrOrrPrrQrrRrrSrrTr:rUrrzdict[IntStrT, DataFrame])r)4r[z str | int | list[IntStrT] | Noner>rr?rr@rrArrBrrCrrDrrErrFrrGrrHrrJrrKrrLrrMrrNrrOrrPrrQrrRrrSrrTrrUrrbrrz$DataFrame | dict[IntStrT, DataFrame]rW)rdzFilePath | ReadBuffer[bytes]rTrrr)e __future__rcollections.abcrrrrr3 functoolsrrZr rtextwrapr typingr r r rrrrrrrr{r`pandas._configr pandas._libsrpandas._libs.parsersrpandas.compat._optionalrr pandas.errorsrpandas.util._decoratorsrrpandas.util._exceptionsrpandas.util._validatorsrpandas.core.dtypes.commonrr r!r"pandas.core.framer#pandas.core.shared_docsr$pandas.util.versionr%pandas.io.commonr&r'r(r)pandas.io.excel._utilr*r+r,r-r.pandas.io.parsersr/pandas.io.parsers.readersr0typesr1pandas._typingr2r3r4r5r6r7r8r9r:r;joinsorted_read_excel_docr]rrkrmrr^r_rmaprr]rirerXr_r\rs+"     !.)57(0' )6#   qd 6;;vm, -rVLerMffgY|  # *-5825  NQCF-0.1EH&),/47&)25C## ' # 3 #0# # # L# A!#"+##$,%#&C'#( )#,-#./#01#2$3#4*5#627#89#:;#<=#>?#@$A#B0C#DE# #L *-5825  NQCF-0.1EH&),/47&)25C#%# ' # 3 #0# # # L# A!#"+##$,%#&C'#( )#,-#./#01#2$3#4*5#627#89#:;#<=#>?#@$A#B0C#DE# #L\"345 /45T*+5926 !NRCG-1.2EI &+,/NN48 -125..!%CT0T ' T 3 T 0 T T T LTAT +!T",#T$C%T& 'T*+T,-T./T0$1T2*3T425T67T89T:;T<=T>+?T@0ATBCTD*ET6Tn\ " }*gj)}*@ \"345n'*%n6nb   C=*::; < \"345.2<1<*<<6<~``r_