_base.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  1. from __future__ import annotations
  2. import abc
  3. import datetime
  4. from functools import partial
  5. from io import BytesIO
  6. import os
  7. from textwrap import fill
  8. from types import TracebackType
  9. from typing import (
  10. IO,
  11. Any,
  12. Callable,
  13. Hashable,
  14. Iterable,
  15. List,
  16. Literal,
  17. Mapping,
  18. Sequence,
  19. Union,
  20. cast,
  21. overload,
  22. )
  23. import zipfile
  24. from pandas._config import config
  25. from pandas._libs import lib
  26. from pandas._libs.parsers import STR_NA_VALUES
  27. from pandas._typing import (
  28. DtypeArg,
  29. DtypeBackend,
  30. FilePath,
  31. IntStrT,
  32. ReadBuffer,
  33. StorageOptions,
  34. WriteExcelBuffer,
  35. )
  36. from pandas.compat._optional import (
  37. get_version,
  38. import_optional_dependency,
  39. )
  40. from pandas.errors import EmptyDataError
  41. from pandas.util._decorators import (
  42. Appender,
  43. doc,
  44. )
  45. from pandas.util._validators import check_dtype_backend
  46. from pandas.core.dtypes.common import (
  47. is_bool,
  48. is_float,
  49. is_integer,
  50. is_list_like,
  51. )
  52. from pandas.core.frame import DataFrame
  53. from pandas.core.shared_docs import _shared_docs
  54. from pandas.util.version import Version
  55. from pandas.io.common import (
  56. IOHandles,
  57. get_handle,
  58. stringify_path,
  59. validate_header_arg,
  60. )
  61. from pandas.io.excel._util import (
  62. fill_mi_header,
  63. get_default_engine,
  64. get_writer,
  65. maybe_convert_usecols,
  66. pop_header_name,
  67. )
  68. from pandas.io.parsers import TextParser
  69. from pandas.io.parsers.readers import validate_integer
  70. _read_excel_doc = (
  71. """
  72. Read an Excel file into a pandas DataFrame.
  73. Supports `xls`, `xlsx`, `xlsm`, `xlsb`, `odf`, `ods` and `odt` file extensions
  74. read from a local filesystem or URL. Supports an option to read
  75. a single sheet or a list of sheets.
  76. Parameters
  77. ----------
  78. io : str, bytes, ExcelFile, xlrd.Book, path object, or file-like object
  79. Any valid string path is acceptable. The string could be a URL. Valid
  80. URL schemes include http, ftp, s3, and file. For file URLs, a host is
  81. expected. A local file could be: ``file://localhost/path/to/table.xlsx``.
  82. If you want to pass in a path object, pandas accepts any ``os.PathLike``.
  83. By file-like object, we refer to objects with a ``read()`` method,
  84. such as a file handle (e.g. via builtin ``open`` function)
  85. or ``StringIO``.
  86. sheet_name : str, int, list, or None, default 0
  87. Strings are used for sheet names. Integers are used in zero-indexed
  88. sheet positions (chart sheets do not count as a sheet position).
  89. Lists of strings/integers are used to request multiple sheets.
  90. Specify None to get all worksheets.
  91. Available cases:
  92. * Defaults to ``0``: 1st sheet as a `DataFrame`
  93. * ``1``: 2nd sheet as a `DataFrame`
  94. * ``"Sheet1"``: Load sheet with name "Sheet1"
  95. * ``[0, 1, "Sheet5"]``: Load first, second and sheet named "Sheet5"
  96. as a dict of `DataFrame`
  97. * None: All worksheets.
  98. header : int, list of int, default 0
  99. Row (0-indexed) to use for the column labels of the parsed
  100. DataFrame. If a list of integers is passed those row positions will
  101. be combined into a ``MultiIndex``. Use None if there is no header.
  102. names : array-like, default None
  103. List of column names to use. If file contains no header row,
  104. then you should explicitly pass header=None.
  105. index_col : int, list of int, default None
  106. Column (0-indexed) to use as the row labels of the DataFrame.
  107. Pass None if there is no such column. If a list is passed,
  108. those columns will be combined into a ``MultiIndex``. If a
  109. subset of data is selected with ``usecols``, index_col
  110. is based on the subset.
  111. Missing values will be forward filled to allow roundtripping with
  112. ``to_excel`` for ``merged_cells=True``. To avoid forward filling the
  113. missing values use ``set_index`` after reading the data instead of
  114. ``index_col``.
  115. usecols : str, list-like, or callable, default None
  116. * If None, then parse all columns.
  117. * If str, then indicates comma separated list of Excel column letters
  118. and column ranges (e.g. "A:E" or "A,C,E:F"). Ranges are inclusive of
  119. both sides.
  120. * If list of int, then indicates list of column numbers to be parsed
  121. (0-indexed).
  122. * If list of string, then indicates list of column names to be parsed.
  123. * If callable, then evaluate each column name against it and parse the
  124. column if the callable returns ``True``.
  125. Returns a subset of the columns according to behavior above.
  126. dtype : Type name or dict of column -> type, default None
  127. Data type for data or columns. E.g. {{'a': np.float64, 'b': np.int32}}
  128. Use `object` to preserve data as stored in Excel and not interpret dtype.
  129. If converters are specified, they will be applied INSTEAD
  130. of dtype conversion.
  131. engine : str, default None
  132. If io is not a buffer or path, this must be set to identify io.
  133. Supported engines: "xlrd", "openpyxl", "odf", "pyxlsb".
  134. Engine compatibility :
  135. - "xlrd" supports old-style Excel files (.xls).
  136. - "openpyxl" supports newer Excel file formats.
  137. - "odf" supports OpenDocument file formats (.odf, .ods, .odt).
  138. - "pyxlsb" supports Binary Excel files.
  139. .. versionchanged:: 1.2.0
  140. The engine `xlrd <https://xlrd.readthedocs.io/en/latest/>`_
  141. now only supports old-style ``.xls`` files.
  142. When ``engine=None``, the following logic will be
  143. used to determine the engine:
  144. - If ``path_or_buffer`` is an OpenDocument format (.odf, .ods, .odt),
  145. then `odf <https://pypi.org/project/odfpy/>`_ will be used.
  146. - Otherwise if ``path_or_buffer`` is an xls format,
  147. ``xlrd`` will be used.
  148. - Otherwise if ``path_or_buffer`` is in xlsb format,
  149. ``pyxlsb`` will be used.
  150. .. versionadded:: 1.3.0
  151. - Otherwise ``openpyxl`` will be used.
  152. .. versionchanged:: 1.3.0
  153. converters : dict, default None
  154. Dict of functions for converting values in certain columns. Keys can
  155. either be integers or column labels, values are functions that take one
  156. input argument, the Excel cell content, and return the transformed
  157. content.
  158. true_values : list, default None
  159. Values to consider as True.
  160. false_values : list, default None
  161. Values to consider as False.
  162. skiprows : list-like, int, or callable, optional
  163. Line numbers to skip (0-indexed) or number of lines to skip (int) at the
  164. start of the file. If callable, the callable function will be evaluated
  165. against the row indices, returning True if the row should be skipped and
  166. False otherwise. An example of a valid callable argument would be ``lambda
  167. x: x in [0, 2]``.
  168. nrows : int, default None
  169. Number of rows to parse.
  170. na_values : scalar, str, list-like, or dict, default None
  171. Additional strings to recognize as NA/NaN. If dict passed, specific
  172. per-column NA values. By default the following values are interpreted
  173. as NaN: '"""
  174. + fill("', '".join(sorted(STR_NA_VALUES)), 70, subsequent_indent=" ")
  175. + """'.
  176. keep_default_na : bool, default True
  177. Whether or not to include the default NaN values when parsing the data.
  178. Depending on whether `na_values` is passed in, the behavior is as follows:
  179. * If `keep_default_na` is True, and `na_values` are specified, `na_values`
  180. is appended to the default NaN values used for parsing.
  181. * If `keep_default_na` is True, and `na_values` are not specified, only
  182. the default NaN values are used for parsing.
  183. * If `keep_default_na` is False, and `na_values` are specified, only
  184. the NaN values specified `na_values` are used for parsing.
  185. * If `keep_default_na` is False, and `na_values` are not specified, no
  186. strings will be parsed as NaN.
  187. Note that if `na_filter` is passed in as False, the `keep_default_na` and
  188. `na_values` parameters will be ignored.
  189. na_filter : bool, default True
  190. Detect missing value markers (empty strings and the value of na_values). In
  191. data without any NAs, passing na_filter=False can improve the performance
  192. of reading a large file.
  193. verbose : bool, default False
  194. Indicate number of NA values placed in non-numeric columns.
  195. parse_dates : bool, list-like, or dict, default False
  196. The behavior is as follows:
  197. * bool. If True -> try parsing the index.
  198. * list of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3
  199. each as a separate date column.
  200. * list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as
  201. a single date column.
  202. * dict, e.g. {{'foo' : [1, 3]}} -> parse columns 1, 3 as date and call
  203. result 'foo'
  204. If a column or index contains an unparsable date, the entire column or
  205. index will be returned unaltered as an object data type. If you don`t want to
  206. parse some cells as date just change their type in Excel to "Text".
  207. For non-standard datetime parsing, use ``pd.to_datetime`` after ``pd.read_excel``.
  208. Note: A fast-path exists for iso8601-formatted dates.
  209. date_parser : function, optional
  210. Function to use for converting a sequence of string columns to an array of
  211. datetime instances. The default uses ``dateutil.parser.parser`` to do the
  212. conversion. Pandas will try to call `date_parser` in three different ways,
  213. advancing to the next if an exception occurs: 1) Pass one or more arrays
  214. (as defined by `parse_dates`) as arguments; 2) concatenate (row-wise) the
  215. string values from the columns defined by `parse_dates` into a single array
  216. and pass that; and 3) call `date_parser` once for each row using one or
  217. more strings (corresponding to the columns defined by `parse_dates`) as
  218. arguments.
  219. .. deprecated:: 2.0.0
  220. Use ``date_format`` instead, or read in as ``object`` and then apply
  221. :func:`to_datetime` as-needed.
  222. date_format : str or dict of column -> format, default ``None``
  223. If used in conjunction with ``parse_dates``, will parse dates according to this
  224. format. For anything more complex,
  225. please read in as ``object`` and then apply :func:`to_datetime` as-needed.
  226. .. versionadded:: 2.0.0
  227. thousands : str, default None
  228. Thousands separator for parsing string columns to numeric. Note that
  229. this parameter is only necessary for columns stored as TEXT in Excel,
  230. any numeric columns will automatically be parsed, regardless of display
  231. format.
  232. decimal : str, default '.'
  233. Character to recognize as decimal point for parsing string columns to numeric.
  234. Note that this parameter is only necessary for columns stored as TEXT in Excel,
  235. any numeric columns will automatically be parsed, regardless of display
  236. format.(e.g. use ',' for European data).
  237. .. versionadded:: 1.4.0
  238. comment : str, default None
  239. Comments out remainder of line. Pass a character or characters to this
  240. argument to indicate comments in the input file. Any data between the
  241. comment string and the end of the current line is ignored.
  242. skipfooter : int, default 0
  243. Rows at the end to skip (0-indexed).
  244. {storage_options}
  245. .. versionadded:: 1.2.0
  246. dtype_backend : {{"numpy_nullable", "pyarrow"}}, defaults to NumPy backed DataFrames
  247. Which dtype_backend to use, e.g. whether a DataFrame should have NumPy
  248. arrays, nullable dtypes are used for all dtypes that have a nullable
  249. implementation when "numpy_nullable" is set, pyarrow is used for all
  250. dtypes if "pyarrow" is set.
  251. The dtype_backends are still experimential.
  252. .. versionadded:: 2.0
  253. Returns
  254. -------
  255. DataFrame or dict of DataFrames
  256. DataFrame from the passed in Excel file. See notes in sheet_name
  257. argument for more information on when a dict of DataFrames is returned.
  258. See Also
  259. --------
  260. DataFrame.to_excel : Write DataFrame to an Excel file.
  261. DataFrame.to_csv : Write DataFrame to a comma-separated values (csv) file.
  262. read_csv : Read a comma-separated values (csv) file into DataFrame.
  263. read_fwf : Read a table of fixed-width formatted lines into DataFrame.
  264. Examples
  265. --------
  266. The file can be read using the file name as string or an open file object:
  267. >>> pd.read_excel('tmp.xlsx', index_col=0) # doctest: +SKIP
  268. Name Value
  269. 0 string1 1
  270. 1 string2 2
  271. 2 #Comment 3
  272. >>> pd.read_excel(open('tmp.xlsx', 'rb'),
  273. ... sheet_name='Sheet3') # doctest: +SKIP
  274. Unnamed: 0 Name Value
  275. 0 0 string1 1
  276. 1 1 string2 2
  277. 2 2 #Comment 3
  278. Index and header can be specified via the `index_col` and `header` arguments
  279. >>> pd.read_excel('tmp.xlsx', index_col=None, header=None) # doctest: +SKIP
  280. 0 1 2
  281. 0 NaN Name Value
  282. 1 0.0 string1 1
  283. 2 1.0 string2 2
  284. 3 2.0 #Comment 3
  285. Column types are inferred but can be explicitly specified
  286. >>> pd.read_excel('tmp.xlsx', index_col=0,
  287. ... dtype={{'Name': str, 'Value': float}}) # doctest: +SKIP
  288. Name Value
  289. 0 string1 1.0
  290. 1 string2 2.0
  291. 2 #Comment 3.0
  292. True, False, and NA values, and thousands separators have defaults,
  293. but can be explicitly specified, too. Supply the values you would like
  294. as strings or lists of strings!
  295. >>> pd.read_excel('tmp.xlsx', index_col=0,
  296. ... na_values=['string1', 'string2']) # doctest: +SKIP
  297. Name Value
  298. 0 NaN 1
  299. 1 NaN 2
  300. 2 #Comment 3
  301. Comment lines in the excel input file can be skipped using the `comment` kwarg
  302. >>> pd.read_excel('tmp.xlsx', index_col=0, comment='#') # doctest: +SKIP
  303. Name Value
  304. 0 string1 1.0
  305. 1 string2 2.0
  306. 2 None NaN
  307. """
  308. )
  309. @overload
  310. def read_excel(
  311. io,
  312. # sheet name is str or int -> DataFrame
  313. sheet_name: str | int = ...,
  314. *,
  315. header: int | Sequence[int] | None = ...,
  316. names: list[str] | None = ...,
  317. index_col: int | Sequence[int] | None = ...,
  318. usecols: int
  319. | str
  320. | Sequence[int]
  321. | Sequence[str]
  322. | Callable[[str], bool]
  323. | None = ...,
  324. dtype: DtypeArg | None = ...,
  325. engine: Literal["xlrd", "openpyxl", "odf", "pyxlsb"] | None = ...,
  326. converters: dict[str, Callable] | dict[int, Callable] | None = ...,
  327. true_values: Iterable[Hashable] | None = ...,
  328. false_values: Iterable[Hashable] | None = ...,
  329. skiprows: Sequence[int] | int | Callable[[int], object] | None = ...,
  330. nrows: int | None = ...,
  331. na_values=...,
  332. keep_default_na: bool = ...,
  333. na_filter: bool = ...,
  334. verbose: bool = ...,
  335. parse_dates: list | dict | bool = ...,
  336. date_parser: Callable | lib.NoDefault = ...,
  337. date_format: dict[Hashable, str] | str | None = ...,
  338. thousands: str | None = ...,
  339. decimal: str = ...,
  340. comment: str | None = ...,
  341. skipfooter: int = ...,
  342. storage_options: StorageOptions = ...,
  343. dtype_backend: DtypeBackend | lib.NoDefault = ...,
  344. ) -> DataFrame:
  345. ...
  346. @overload
  347. def read_excel(
  348. io,
  349. # sheet name is list or None -> dict[IntStrT, DataFrame]
  350. sheet_name: list[IntStrT] | None,
  351. *,
  352. header: int | Sequence[int] | None = ...,
  353. names: list[str] | None = ...,
  354. index_col: int | Sequence[int] | None = ...,
  355. usecols: int
  356. | str
  357. | Sequence[int]
  358. | Sequence[str]
  359. | Callable[[str], bool]
  360. | None = ...,
  361. dtype: DtypeArg | None = ...,
  362. engine: Literal["xlrd", "openpyxl", "odf", "pyxlsb"] | None = ...,
  363. converters: dict[str, Callable] | dict[int, Callable] | None = ...,
  364. true_values: Iterable[Hashable] | None = ...,
  365. false_values: Iterable[Hashable] | None = ...,
  366. skiprows: Sequence[int] | int | Callable[[int], object] | None = ...,
  367. nrows: int | None = ...,
  368. na_values=...,
  369. keep_default_na: bool = ...,
  370. na_filter: bool = ...,
  371. verbose: bool = ...,
  372. parse_dates: list | dict | bool = ...,
  373. date_parser: Callable | lib.NoDefault = ...,
  374. date_format: dict[Hashable, str] | str | None = ...,
  375. thousands: str | None = ...,
  376. decimal: str = ...,
  377. comment: str | None = ...,
  378. skipfooter: int = ...,
  379. storage_options: StorageOptions = ...,
  380. dtype_backend: DtypeBackend | lib.NoDefault = ...,
  381. ) -> dict[IntStrT, DataFrame]:
  382. ...
  383. @doc(storage_options=_shared_docs["storage_options"])
  384. @Appender(_read_excel_doc)
  385. def read_excel(
  386. io,
  387. sheet_name: str | int | list[IntStrT] | None = 0,
  388. *,
  389. header: int | Sequence[int] | None = 0,
  390. names: list[str] | None = None,
  391. index_col: int | Sequence[int] | None = None,
  392. usecols: int
  393. | str
  394. | Sequence[int]
  395. | Sequence[str]
  396. | Callable[[str], bool]
  397. | None = None,
  398. dtype: DtypeArg | None = None,
  399. engine: Literal["xlrd", "openpyxl", "odf", "pyxlsb"] | None = None,
  400. converters: dict[str, Callable] | dict[int, Callable] | None = None,
  401. true_values: Iterable[Hashable] | None = None,
  402. false_values: Iterable[Hashable] | None = None,
  403. skiprows: Sequence[int] | int | Callable[[int], object] | None = None,
  404. nrows: int | None = None,
  405. na_values=None,
  406. keep_default_na: bool = True,
  407. na_filter: bool = True,
  408. verbose: bool = False,
  409. parse_dates: list | dict | bool = False,
  410. date_parser: Callable | lib.NoDefault = lib.no_default,
  411. date_format: dict[Hashable, str] | str | None = None,
  412. thousands: str | None = None,
  413. decimal: str = ".",
  414. comment: str | None = None,
  415. skipfooter: int = 0,
  416. storage_options: StorageOptions = None,
  417. dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,
  418. ) -> DataFrame | dict[IntStrT, DataFrame]:
  419. check_dtype_backend(dtype_backend)
  420. should_close = False
  421. if not isinstance(io, ExcelFile):
  422. should_close = True
  423. io = ExcelFile(io, storage_options=storage_options, engine=engine)
  424. elif engine and engine != io.engine:
  425. raise ValueError(
  426. "Engine should not be specified when passing "
  427. "an ExcelFile - ExcelFile already has the engine set"
  428. )
  429. try:
  430. data = io.parse(
  431. sheet_name=sheet_name,
  432. header=header,
  433. names=names,
  434. index_col=index_col,
  435. usecols=usecols,
  436. dtype=dtype,
  437. converters=converters,
  438. true_values=true_values,
  439. false_values=false_values,
  440. skiprows=skiprows,
  441. nrows=nrows,
  442. na_values=na_values,
  443. keep_default_na=keep_default_na,
  444. na_filter=na_filter,
  445. verbose=verbose,
  446. parse_dates=parse_dates,
  447. date_parser=date_parser,
  448. date_format=date_format,
  449. thousands=thousands,
  450. decimal=decimal,
  451. comment=comment,
  452. skipfooter=skipfooter,
  453. dtype_backend=dtype_backend,
  454. )
  455. finally:
  456. # make sure to close opened file handles
  457. if should_close:
  458. io.close()
  459. return data
  460. class BaseExcelReader(metaclass=abc.ABCMeta):
  461. def __init__(
  462. self, filepath_or_buffer, storage_options: StorageOptions = None
  463. ) -> None:
  464. # First argument can also be bytes, so create a buffer
  465. if isinstance(filepath_or_buffer, bytes):
  466. filepath_or_buffer = BytesIO(filepath_or_buffer)
  467. self.handles = IOHandles(
  468. handle=filepath_or_buffer, compression={"method": None}
  469. )
  470. if not isinstance(filepath_or_buffer, (ExcelFile, self._workbook_class)):
  471. self.handles = get_handle(
  472. filepath_or_buffer, "rb", storage_options=storage_options, is_text=False
  473. )
  474. if isinstance(self.handles.handle, self._workbook_class):
  475. self.book = self.handles.handle
  476. elif hasattr(self.handles.handle, "read"):
  477. # N.B. xlrd.Book has a read attribute too
  478. self.handles.handle.seek(0)
  479. try:
  480. self.book = self.load_workbook(self.handles.handle)
  481. except Exception:
  482. self.close()
  483. raise
  484. else:
  485. raise ValueError(
  486. "Must explicitly set engine if not passing in buffer or path for io."
  487. )
  488. @property
  489. @abc.abstractmethod
  490. def _workbook_class(self):
  491. pass
  492. @abc.abstractmethod
  493. def load_workbook(self, filepath_or_buffer):
  494. pass
  495. def close(self) -> None:
  496. if hasattr(self, "book"):
  497. if hasattr(self.book, "close"):
  498. # pyxlsb: opens a TemporaryFile
  499. # openpyxl: https://stackoverflow.com/questions/31416842/
  500. # openpyxl-does-not-close-excel-workbook-in-read-only-mode
  501. self.book.close()
  502. elif hasattr(self.book, "release_resources"):
  503. # xlrd
  504. # https://github.com/python-excel/xlrd/blob/2.0.1/xlrd/book.py#L548
  505. self.book.release_resources()
  506. self.handles.close()
  507. @property
  508. @abc.abstractmethod
  509. def sheet_names(self) -> list[str]:
  510. pass
  511. @abc.abstractmethod
  512. def get_sheet_by_name(self, name: str):
  513. pass
  514. @abc.abstractmethod
  515. def get_sheet_by_index(self, index: int):
  516. pass
  517. @abc.abstractmethod
  518. def get_sheet_data(self, sheet, rows: int | None = None):
  519. pass
  520. def raise_if_bad_sheet_by_index(self, index: int) -> None:
  521. n_sheets = len(self.sheet_names)
  522. if index >= n_sheets:
  523. raise ValueError(
  524. f"Worksheet index {index} is invalid, {n_sheets} worksheets found"
  525. )
  526. def raise_if_bad_sheet_by_name(self, name: str) -> None:
  527. if name not in self.sheet_names:
  528. raise ValueError(f"Worksheet named '{name}' not found")
  529. def _check_skiprows_func(
  530. self,
  531. skiprows: Callable,
  532. rows_to_use: int,
  533. ) -> int:
  534. """
  535. Determine how many file rows are required to obtain `nrows` data
  536. rows when `skiprows` is a function.
  537. Parameters
  538. ----------
  539. skiprows : function
  540. The function passed to read_excel by the user.
  541. rows_to_use : int
  542. The number of rows that will be needed for the header and
  543. the data.
  544. Returns
  545. -------
  546. int
  547. """
  548. i = 0
  549. rows_used_so_far = 0
  550. while rows_used_so_far < rows_to_use:
  551. if not skiprows(i):
  552. rows_used_so_far += 1
  553. i += 1
  554. return i
  555. def _calc_rows(
  556. self,
  557. header: int | Sequence[int] | None,
  558. index_col: int | Sequence[int] | None,
  559. skiprows: Sequence[int] | int | Callable[[int], object] | None,
  560. nrows: int | None,
  561. ) -> int | None:
  562. """
  563. If nrows specified, find the number of rows needed from the
  564. file, otherwise return None.
  565. Parameters
  566. ----------
  567. header : int, list of int, or None
  568. See read_excel docstring.
  569. index_col : int, list of int, or None
  570. See read_excel docstring.
  571. skiprows : list-like, int, callable, or None
  572. See read_excel docstring.
  573. nrows : int or None
  574. See read_excel docstring.
  575. Returns
  576. -------
  577. int or None
  578. """
  579. if nrows is None:
  580. return None
  581. if header is None:
  582. header_rows = 1
  583. elif is_integer(header):
  584. header = cast(int, header)
  585. header_rows = 1 + header
  586. else:
  587. header = cast(Sequence, header)
  588. header_rows = 1 + header[-1]
  589. # If there is a MultiIndex header and an index then there is also
  590. # a row containing just the index name(s)
  591. if is_list_like(header) and index_col is not None:
  592. header = cast(Sequence, header)
  593. if len(header) > 1:
  594. header_rows += 1
  595. if skiprows is None:
  596. return header_rows + nrows
  597. if is_integer(skiprows):
  598. skiprows = cast(int, skiprows)
  599. return header_rows + nrows + skiprows
  600. if is_list_like(skiprows):
  601. def f(skiprows: Sequence, x: int) -> bool:
  602. return x in skiprows
  603. skiprows = cast(Sequence, skiprows)
  604. return self._check_skiprows_func(partial(f, skiprows), header_rows + nrows)
  605. if callable(skiprows):
  606. return self._check_skiprows_func(
  607. skiprows,
  608. header_rows + nrows,
  609. )
  610. # else unexpected skiprows type: read_excel will not optimize
  611. # the number of rows read from file
  612. return None
  613. def parse(
  614. self,
  615. sheet_name: str | int | list[int] | list[str] | None = 0,
  616. header: int | Sequence[int] | None = 0,
  617. names=None,
  618. index_col: int | Sequence[int] | None = None,
  619. usecols=None,
  620. dtype: DtypeArg | None = None,
  621. true_values: Iterable[Hashable] | None = None,
  622. false_values: Iterable[Hashable] | None = None,
  623. skiprows: Sequence[int] | int | Callable[[int], object] | None = None,
  624. nrows: int | None = None,
  625. na_values=None,
  626. verbose: bool = False,
  627. parse_dates: list | dict | bool = False,
  628. date_parser: Callable | lib.NoDefault = lib.no_default,
  629. date_format: dict[Hashable, str] | str | None = None,
  630. thousands: str | None = None,
  631. decimal: str = ".",
  632. comment: str | None = None,
  633. skipfooter: int = 0,
  634. dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,
  635. **kwds,
  636. ):
  637. validate_header_arg(header)
  638. validate_integer("nrows", nrows)
  639. ret_dict = False
  640. # Keep sheetname to maintain backwards compatibility.
  641. sheets: list[int] | list[str]
  642. if isinstance(sheet_name, list):
  643. sheets = sheet_name
  644. ret_dict = True
  645. elif sheet_name is None:
  646. sheets = self.sheet_names
  647. ret_dict = True
  648. elif isinstance(sheet_name, str):
  649. sheets = [sheet_name]
  650. else:
  651. sheets = [sheet_name]
  652. # handle same-type duplicates.
  653. sheets = cast(Union[List[int], List[str]], list(dict.fromkeys(sheets).keys()))
  654. output = {}
  655. last_sheetname = None
  656. for asheetname in sheets:
  657. last_sheetname = asheetname
  658. if verbose:
  659. print(f"Reading sheet {asheetname}")
  660. if isinstance(asheetname, str):
  661. sheet = self.get_sheet_by_name(asheetname)
  662. else: # assume an integer if not a string
  663. sheet = self.get_sheet_by_index(asheetname)
  664. file_rows_needed = self._calc_rows(header, index_col, skiprows, nrows)
  665. data = self.get_sheet_data(sheet, file_rows_needed)
  666. if hasattr(sheet, "close"):
  667. # pyxlsb opens two TemporaryFiles
  668. sheet.close()
  669. usecols = maybe_convert_usecols(usecols)
  670. if not data:
  671. output[asheetname] = DataFrame()
  672. continue
  673. is_list_header = False
  674. is_len_one_list_header = False
  675. if is_list_like(header):
  676. assert isinstance(header, Sequence)
  677. is_list_header = True
  678. if len(header) == 1:
  679. is_len_one_list_header = True
  680. if is_len_one_list_header:
  681. header = cast(Sequence[int], header)[0]
  682. # forward fill and pull out names for MultiIndex column
  683. header_names = None
  684. if header is not None and is_list_like(header):
  685. assert isinstance(header, Sequence)
  686. header_names = []
  687. control_row = [True] * len(data[0])
  688. for row in header:
  689. if is_integer(skiprows):
  690. assert isinstance(skiprows, int)
  691. row += skiprows
  692. if row > len(data) - 1:
  693. raise ValueError(
  694. f"header index {row} exceeds maximum index "
  695. f"{len(data) - 1} of data.",
  696. )
  697. data[row], control_row = fill_mi_header(data[row], control_row)
  698. if index_col is not None:
  699. header_name, _ = pop_header_name(data[row], index_col)
  700. header_names.append(header_name)
  701. # If there is a MultiIndex header and an index then there is also
  702. # a row containing just the index name(s)
  703. has_index_names = False
  704. if is_list_header and not is_len_one_list_header and index_col is not None:
  705. index_col_list: Sequence[int]
  706. if isinstance(index_col, int):
  707. index_col_list = [index_col]
  708. else:
  709. assert isinstance(index_col, Sequence)
  710. index_col_list = index_col
  711. # We have to handle mi without names. If any of the entries in the data
  712. # columns are not empty, this is a regular row
  713. assert isinstance(header, Sequence)
  714. if len(header) < len(data):
  715. potential_index_names = data[len(header)]
  716. potential_data = [
  717. x
  718. for i, x in enumerate(potential_index_names)
  719. if not control_row[i] and i not in index_col_list
  720. ]
  721. has_index_names = all(x == "" or x is None for x in potential_data)
  722. if is_list_like(index_col):
  723. # Forward fill values for MultiIndex index.
  724. if header is None:
  725. offset = 0
  726. elif isinstance(header, int):
  727. offset = 1 + header
  728. else:
  729. offset = 1 + max(header)
  730. # GH34673: if MultiIndex names present and not defined in the header,
  731. # offset needs to be incremented so that forward filling starts
  732. # from the first MI value instead of the name
  733. if has_index_names:
  734. offset += 1
  735. # Check if we have an empty dataset
  736. # before trying to collect data.
  737. if offset < len(data):
  738. assert isinstance(index_col, Sequence)
  739. for col in index_col:
  740. last = data[offset][col]
  741. for row in range(offset + 1, len(data)):
  742. if data[row][col] == "" or data[row][col] is None:
  743. data[row][col] = last
  744. else:
  745. last = data[row][col]
  746. # GH 12292 : error when read one empty column from excel file
  747. try:
  748. parser = TextParser(
  749. data,
  750. names=names,
  751. header=header,
  752. index_col=index_col,
  753. has_index_names=has_index_names,
  754. dtype=dtype,
  755. true_values=true_values,
  756. false_values=false_values,
  757. skiprows=skiprows,
  758. nrows=nrows,
  759. na_values=na_values,
  760. skip_blank_lines=False, # GH 39808
  761. parse_dates=parse_dates,
  762. date_parser=date_parser,
  763. date_format=date_format,
  764. thousands=thousands,
  765. decimal=decimal,
  766. comment=comment,
  767. skipfooter=skipfooter,
  768. usecols=usecols,
  769. dtype_backend=dtype_backend,
  770. **kwds,
  771. )
  772. output[asheetname] = parser.read(nrows=nrows)
  773. if header_names:
  774. output[asheetname].columns = output[asheetname].columns.set_names(
  775. header_names
  776. )
  777. except EmptyDataError:
  778. # No Data, return an empty DataFrame
  779. output[asheetname] = DataFrame()
  780. except Exception as err:
  781. err.args = (f"{err.args[0]} (sheet: {asheetname})", *err.args[1:])
  782. raise err
  783. if last_sheetname is None:
  784. raise ValueError("Sheet name is an empty list")
  785. if ret_dict:
  786. return output
  787. else:
  788. return output[last_sheetname]
  789. @doc(storage_options=_shared_docs["storage_options"])
  790. class ExcelWriter(metaclass=abc.ABCMeta):
  791. """
  792. Class for writing DataFrame objects into excel sheets.
  793. Default is to use:
  794. * `xlsxwriter <https://pypi.org/project/XlsxWriter/>`__ for xlsx files if xlsxwriter
  795. is installed otherwise `openpyxl <https://pypi.org/project/openpyxl/>`__
  796. * `odswriter <https://pypi.org/project/odswriter/>`__ for ods files
  797. See ``DataFrame.to_excel`` for typical usage.
  798. The writer should be used as a context manager. Otherwise, call `close()` to save
  799. and close any opened file handles.
  800. Parameters
  801. ----------
  802. path : str or typing.BinaryIO
  803. Path to xls or xlsx or ods file.
  804. engine : str (optional)
  805. Engine to use for writing. If None, defaults to
  806. ``io.excel.<extension>.writer``. NOTE: can only be passed as a keyword
  807. argument.
  808. date_format : str, default None
  809. Format string for dates written into Excel files (e.g. 'YYYY-MM-DD').
  810. datetime_format : str, default None
  811. Format string for datetime objects written into Excel files.
  812. (e.g. 'YYYY-MM-DD HH:MM:SS').
  813. mode : {{'w', 'a'}}, default 'w'
  814. File mode to use (write or append). Append does not work with fsspec URLs.
  815. {storage_options}
  816. .. versionadded:: 1.2.0
  817. if_sheet_exists : {{'error', 'new', 'replace', 'overlay'}}, default 'error'
  818. How to behave when trying to write to a sheet that already
  819. exists (append mode only).
  820. * error: raise a ValueError.
  821. * new: Create a new sheet, with a name determined by the engine.
  822. * replace: Delete the contents of the sheet before writing to it.
  823. * overlay: Write contents to the existing sheet without removing the old
  824. contents.
  825. .. versionadded:: 1.3.0
  826. .. versionchanged:: 1.4.0
  827. Added ``overlay`` option
  828. engine_kwargs : dict, optional
  829. Keyword arguments to be passed into the engine. These will be passed to
  830. the following functions of the respective engines:
  831. * xlsxwriter: ``xlsxwriter.Workbook(file, **engine_kwargs)``
  832. * openpyxl (write mode): ``openpyxl.Workbook(**engine_kwargs)``
  833. * openpyxl (append mode): ``openpyxl.load_workbook(file, **engine_kwargs)``
  834. * odswriter: ``odf.opendocument.OpenDocumentSpreadsheet(**engine_kwargs)``
  835. .. versionadded:: 1.3.0
  836. Notes
  837. -----
  838. For compatibility with CSV writers, ExcelWriter serializes lists
  839. and dicts to strings before writing.
  840. Examples
  841. --------
  842. Default usage:
  843. >>> df = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"]) # doctest: +SKIP
  844. >>> with pd.ExcelWriter("path_to_file.xlsx") as writer:
  845. ... df.to_excel(writer) # doctest: +SKIP
  846. To write to separate sheets in a single file:
  847. >>> df1 = pd.DataFrame([["AAA", "BBB"]], columns=["Spam", "Egg"]) # doctest: +SKIP
  848. >>> df2 = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"]) # doctest: +SKIP
  849. >>> with pd.ExcelWriter("path_to_file.xlsx") as writer:
  850. ... df1.to_excel(writer, sheet_name="Sheet1") # doctest: +SKIP
  851. ... df2.to_excel(writer, sheet_name="Sheet2") # doctest: +SKIP
  852. You can set the date format or datetime format:
  853. >>> from datetime import date, datetime # doctest: +SKIP
  854. >>> df = pd.DataFrame(
  855. ... [
  856. ... [date(2014, 1, 31), date(1999, 9, 24)],
  857. ... [datetime(1998, 5, 26, 23, 33, 4), datetime(2014, 2, 28, 13, 5, 13)],
  858. ... ],
  859. ... index=["Date", "Datetime"],
  860. ... columns=["X", "Y"],
  861. ... ) # doctest: +SKIP
  862. >>> with pd.ExcelWriter(
  863. ... "path_to_file.xlsx",
  864. ... date_format="YYYY-MM-DD",
  865. ... datetime_format="YYYY-MM-DD HH:MM:SS"
  866. ... ) as writer:
  867. ... df.to_excel(writer) # doctest: +SKIP
  868. You can also append to an existing Excel file:
  869. >>> with pd.ExcelWriter("path_to_file.xlsx", mode="a", engine="openpyxl") as writer:
  870. ... df.to_excel(writer, sheet_name="Sheet3") # doctest: +SKIP
  871. Here, the `if_sheet_exists` parameter can be set to replace a sheet if it
  872. already exists:
  873. >>> with ExcelWriter(
  874. ... "path_to_file.xlsx",
  875. ... mode="a",
  876. ... engine="openpyxl",
  877. ... if_sheet_exists="replace",
  878. ... ) as writer:
  879. ... df.to_excel(writer, sheet_name="Sheet1") # doctest: +SKIP
  880. You can also write multiple DataFrames to a single sheet. Note that the
  881. ``if_sheet_exists`` parameter needs to be set to ``overlay``:
  882. >>> with ExcelWriter("path_to_file.xlsx",
  883. ... mode="a",
  884. ... engine="openpyxl",
  885. ... if_sheet_exists="overlay",
  886. ... ) as writer:
  887. ... df1.to_excel(writer, sheet_name="Sheet1")
  888. ... df2.to_excel(writer, sheet_name="Sheet1", startcol=3) # doctest: +SKIP
  889. You can store Excel file in RAM:
  890. >>> import io
  891. >>> df = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"])
  892. >>> buffer = io.BytesIO()
  893. >>> with pd.ExcelWriter(buffer) as writer:
  894. ... df.to_excel(writer)
  895. You can pack Excel file into zip archive:
  896. >>> import zipfile # doctest: +SKIP
  897. >>> df = pd.DataFrame([["ABC", "XYZ"]], columns=["Foo", "Bar"]) # doctest: +SKIP
  898. >>> with zipfile.ZipFile("path_to_file.zip", "w") as zf:
  899. ... with zf.open("filename.xlsx", "w") as buffer:
  900. ... with pd.ExcelWriter(buffer) as writer:
  901. ... df.to_excel(writer) # doctest: +SKIP
  902. You can specify additional arguments to the underlying engine:
  903. >>> with pd.ExcelWriter(
  904. ... "path_to_file.xlsx",
  905. ... engine="xlsxwriter",
  906. ... engine_kwargs={{"options": {{"nan_inf_to_errors": True}}}}
  907. ... ) as writer:
  908. ... df.to_excel(writer) # doctest: +SKIP
  909. In append mode, ``engine_kwargs`` are passed through to
  910. openpyxl's ``load_workbook``:
  911. >>> with pd.ExcelWriter(
  912. ... "path_to_file.xlsx",
  913. ... engine="openpyxl",
  914. ... mode="a",
  915. ... engine_kwargs={{"keep_vba": True}}
  916. ... ) as writer:
  917. ... df.to_excel(writer, sheet_name="Sheet2") # doctest: +SKIP
  918. """
  919. # Defining an ExcelWriter implementation (see abstract methods for more...)
  920. # - Mandatory
  921. # - ``write_cells(self, cells, sheet_name=None, startrow=0, startcol=0)``
  922. # --> called to write additional DataFrames to disk
  923. # - ``_supported_extensions`` (tuple of supported extensions), used to
  924. # check that engine supports the given extension.
  925. # - ``_engine`` - string that gives the engine name. Necessary to
  926. # instantiate class directly and bypass ``ExcelWriterMeta`` engine
  927. # lookup.
  928. # - ``save(self)`` --> called to save file to disk
  929. # - Mostly mandatory (i.e. should at least exist)
  930. # - book, cur_sheet, path
  931. # - Optional:
  932. # - ``__init__(self, path, engine=None, **kwargs)`` --> always called
  933. # with path as first argument.
  934. # You also need to register the class with ``register_writer()``.
  935. # Technically, ExcelWriter implementations don't need to subclass
  936. # ExcelWriter.
  937. _engine: str
  938. _supported_extensions: tuple[str, ...]
  939. def __new__(
  940. cls: type[ExcelWriter],
  941. path: FilePath | WriteExcelBuffer | ExcelWriter,
  942. engine: str | None = None,
  943. date_format: str | None = None,
  944. datetime_format: str | None = None,
  945. mode: str = "w",
  946. storage_options: StorageOptions = None,
  947. if_sheet_exists: Literal["error", "new", "replace", "overlay"] | None = None,
  948. engine_kwargs: dict | None = None,
  949. ) -> ExcelWriter:
  950. # only switch class if generic(ExcelWriter)
  951. if cls is ExcelWriter:
  952. if engine is None or (isinstance(engine, str) and engine == "auto"):
  953. if isinstance(path, str):
  954. ext = os.path.splitext(path)[-1][1:]
  955. else:
  956. ext = "xlsx"
  957. try:
  958. engine = config.get_option(f"io.excel.{ext}.writer", silent=True)
  959. if engine == "auto":
  960. engine = get_default_engine(ext, mode="writer")
  961. except KeyError as err:
  962. raise ValueError(f"No engine for filetype: '{ext}'") from err
  963. # for mypy
  964. assert engine is not None
  965. cls = get_writer(engine)
  966. return object.__new__(cls)
  967. # declare external properties you can count on
  968. _path = None
  969. @property
  970. def supported_extensions(self) -> tuple[str, ...]:
  971. """Extensions that writer engine supports."""
  972. return self._supported_extensions
  973. @property
  974. def engine(self) -> str:
  975. """Name of engine."""
  976. return self._engine
  977. @property
  978. @abc.abstractmethod
  979. def sheets(self) -> dict[str, Any]:
  980. """Mapping of sheet names to sheet objects."""
  981. @property
  982. @abc.abstractmethod
  983. def book(self):
  984. """
  985. Book instance. Class type will depend on the engine used.
  986. This attribute can be used to access engine-specific features.
  987. """
  988. @abc.abstractmethod
  989. def _write_cells(
  990. self,
  991. cells,
  992. sheet_name: str | None = None,
  993. startrow: int = 0,
  994. startcol: int = 0,
  995. freeze_panes: tuple[int, int] | None = None,
  996. ) -> None:
  997. """
  998. Write given formatted cells into Excel an excel sheet
  999. Parameters
  1000. ----------
  1001. cells : generator
  1002. cell of formatted data to save to Excel sheet
  1003. sheet_name : str, default None
  1004. Name of Excel sheet, if None, then use self.cur_sheet
  1005. startrow : upper left cell row to dump data frame
  1006. startcol : upper left cell column to dump data frame
  1007. freeze_panes: int tuple of length 2
  1008. contains the bottom-most row and right-most column to freeze
  1009. """
  1010. @abc.abstractmethod
  1011. def _save(self) -> None:
  1012. """
  1013. Save workbook to disk.
  1014. """
  1015. def __init__(
  1016. self,
  1017. path: FilePath | WriteExcelBuffer | ExcelWriter,
  1018. engine: str | None = None,
  1019. date_format: str | None = None,
  1020. datetime_format: str | None = None,
  1021. mode: str = "w",
  1022. storage_options: StorageOptions = None,
  1023. if_sheet_exists: str | None = None,
  1024. engine_kwargs: dict[str, Any] | None = None,
  1025. ) -> None:
  1026. # validate that this engine can handle the extension
  1027. if isinstance(path, str):
  1028. ext = os.path.splitext(path)[-1]
  1029. self.check_extension(ext)
  1030. # use mode to open the file
  1031. if "b" not in mode:
  1032. mode += "b"
  1033. # use "a" for the user to append data to excel but internally use "r+" to let
  1034. # the excel backend first read the existing file and then write any data to it
  1035. mode = mode.replace("a", "r+")
  1036. if if_sheet_exists not in (None, "error", "new", "replace", "overlay"):
  1037. raise ValueError(
  1038. f"'{if_sheet_exists}' is not valid for if_sheet_exists. "
  1039. "Valid options are 'error', 'new', 'replace' and 'overlay'."
  1040. )
  1041. if if_sheet_exists and "r+" not in mode:
  1042. raise ValueError("if_sheet_exists is only valid in append mode (mode='a')")
  1043. if if_sheet_exists is None:
  1044. if_sheet_exists = "error"
  1045. self._if_sheet_exists = if_sheet_exists
  1046. # cast ExcelWriter to avoid adding 'if self._handles is not None'
  1047. self._handles = IOHandles(
  1048. cast(IO[bytes], path), compression={"compression": None}
  1049. )
  1050. if not isinstance(path, ExcelWriter):
  1051. self._handles = get_handle(
  1052. path, mode, storage_options=storage_options, is_text=False
  1053. )
  1054. self._cur_sheet = None
  1055. if date_format is None:
  1056. self._date_format = "YYYY-MM-DD"
  1057. else:
  1058. self._date_format = date_format
  1059. if datetime_format is None:
  1060. self._datetime_format = "YYYY-MM-DD HH:MM:SS"
  1061. else:
  1062. self._datetime_format = datetime_format
  1063. self._mode = mode
  1064. @property
  1065. def date_format(self) -> str:
  1066. """
  1067. Format string for dates written into Excel files (e.g. ‘YYYY-MM-DD’).
  1068. """
  1069. return self._date_format
  1070. @property
  1071. def datetime_format(self) -> str:
  1072. """
  1073. Format string for dates written into Excel files (e.g. ‘YYYY-MM-DD’).
  1074. """
  1075. return self._datetime_format
  1076. @property
  1077. def if_sheet_exists(self) -> str:
  1078. """
  1079. How to behave when writing to a sheet that already exists in append mode.
  1080. """
  1081. return self._if_sheet_exists
  1082. def __fspath__(self) -> str:
  1083. return getattr(self._handles.handle, "name", "")
  1084. def _get_sheet_name(self, sheet_name: str | None) -> str:
  1085. if sheet_name is None:
  1086. sheet_name = self._cur_sheet
  1087. if sheet_name is None: # pragma: no cover
  1088. raise ValueError("Must pass explicit sheet_name or set _cur_sheet property")
  1089. return sheet_name
  1090. def _value_with_fmt(self, val) -> tuple[object, str | None]:
  1091. """
  1092. Convert numpy types to Python types for the Excel writers.
  1093. Parameters
  1094. ----------
  1095. val : object
  1096. Value to be written into cells
  1097. Returns
  1098. -------
  1099. Tuple with the first element being the converted value and the second
  1100. being an optional format
  1101. """
  1102. fmt = None
  1103. if is_integer(val):
  1104. val = int(val)
  1105. elif is_float(val):
  1106. val = float(val)
  1107. elif is_bool(val):
  1108. val = bool(val)
  1109. elif isinstance(val, datetime.datetime):
  1110. fmt = self._datetime_format
  1111. elif isinstance(val, datetime.date):
  1112. fmt = self._date_format
  1113. elif isinstance(val, datetime.timedelta):
  1114. val = val.total_seconds() / 86400
  1115. fmt = "0"
  1116. else:
  1117. val = str(val)
  1118. return val, fmt
  1119. @classmethod
  1120. def check_extension(cls, ext: str) -> Literal[True]:
  1121. """
  1122. checks that path's extension against the Writer's supported
  1123. extensions. If it isn't supported, raises UnsupportedFiletypeError.
  1124. """
  1125. if ext.startswith("."):
  1126. ext = ext[1:]
  1127. if not any(ext in extension for extension in cls._supported_extensions):
  1128. raise ValueError(f"Invalid extension for engine '{cls.engine}': '{ext}'")
  1129. return True
  1130. # Allow use as a contextmanager
  1131. def __enter__(self) -> ExcelWriter:
  1132. return self
  1133. def __exit__(
  1134. self,
  1135. exc_type: type[BaseException] | None,
  1136. exc_value: BaseException | None,
  1137. traceback: TracebackType | None,
  1138. ) -> None:
  1139. self.close()
  1140. def close(self) -> None:
  1141. """synonym for save, to make it more file-like"""
  1142. self._save()
  1143. self._handles.close()
  1144. XLS_SIGNATURES = (
  1145. b"\x09\x00\x04\x00\x07\x00\x10\x00", # BIFF2
  1146. b"\x09\x02\x06\x00\x00\x00\x10\x00", # BIFF3
  1147. b"\x09\x04\x06\x00\x00\x00\x10\x00", # BIFF4
  1148. b"\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1", # Compound File Binary
  1149. )
  1150. ZIP_SIGNATURE = b"PK\x03\x04"
  1151. PEEK_SIZE = max(map(len, XLS_SIGNATURES + (ZIP_SIGNATURE,)))
  1152. @doc(storage_options=_shared_docs["storage_options"])
  1153. def inspect_excel_format(
  1154. content_or_path: FilePath | ReadBuffer[bytes],
  1155. storage_options: StorageOptions = None,
  1156. ) -> str | None:
  1157. """
  1158. Inspect the path or content of an excel file and get its format.
  1159. Adopted from xlrd: https://github.com/python-excel/xlrd.
  1160. Parameters
  1161. ----------
  1162. content_or_path : str or file-like object
  1163. Path to file or content of file to inspect. May be a URL.
  1164. {storage_options}
  1165. Returns
  1166. -------
  1167. str or None
  1168. Format of file if it can be determined.
  1169. Raises
  1170. ------
  1171. ValueError
  1172. If resulting stream is empty.
  1173. BadZipFile
  1174. If resulting stream does not have an XLS signature and is not a valid zipfile.
  1175. """
  1176. if isinstance(content_or_path, bytes):
  1177. content_or_path = BytesIO(content_or_path)
  1178. with get_handle(
  1179. content_or_path, "rb", storage_options=storage_options, is_text=False
  1180. ) as handle:
  1181. stream = handle.handle
  1182. stream.seek(0)
  1183. buf = stream.read(PEEK_SIZE)
  1184. if buf is None:
  1185. raise ValueError("stream is empty")
  1186. assert isinstance(buf, bytes)
  1187. peek = buf
  1188. stream.seek(0)
  1189. if any(peek.startswith(sig) for sig in XLS_SIGNATURES):
  1190. return "xls"
  1191. elif not peek.startswith(ZIP_SIGNATURE):
  1192. return None
  1193. with zipfile.ZipFile(stream) as zf:
  1194. # Workaround for some third party files that use forward slashes and
  1195. # lower case names.
  1196. component_names = [
  1197. name.replace("\\", "/").lower() for name in zf.namelist()
  1198. ]
  1199. if "xl/workbook.xml" in component_names:
  1200. return "xlsx"
  1201. if "xl/workbook.bin" in component_names:
  1202. return "xlsb"
  1203. if "content.xml" in component_names:
  1204. return "ods"
  1205. return "zip"
  1206. class ExcelFile:
  1207. """
  1208. Class for parsing tabular Excel sheets into DataFrame objects.
  1209. See read_excel for more documentation.
  1210. Parameters
  1211. ----------
  1212. path_or_buffer : str, bytes, path object (pathlib.Path or py._path.local.LocalPath),
  1213. A file-like object, xlrd workbook or openpyxl workbook.
  1214. If a string or path object, expected to be a path to a
  1215. .xls, .xlsx, .xlsb, .xlsm, .odf, .ods, or .odt file.
  1216. engine : str, default None
  1217. If io is not a buffer or path, this must be set to identify io.
  1218. Supported engines: ``xlrd``, ``openpyxl``, ``odf``, ``pyxlsb``
  1219. Engine compatibility :
  1220. - ``xlrd`` supports old-style Excel files (.xls).
  1221. - ``openpyxl`` supports newer Excel file formats.
  1222. - ``odf`` supports OpenDocument file formats (.odf, .ods, .odt).
  1223. - ``pyxlsb`` supports Binary Excel files.
  1224. .. versionchanged:: 1.2.0
  1225. The engine `xlrd <https://xlrd.readthedocs.io/en/latest/>`_
  1226. now only supports old-style ``.xls`` files.
  1227. When ``engine=None``, the following logic will be
  1228. used to determine the engine:
  1229. - If ``path_or_buffer`` is an OpenDocument format (.odf, .ods, .odt),
  1230. then `odf <https://pypi.org/project/odfpy/>`_ will be used.
  1231. - Otherwise if ``path_or_buffer`` is an xls format,
  1232. ``xlrd`` will be used.
  1233. - Otherwise if ``path_or_buffer`` is in xlsb format,
  1234. `pyxlsb <https://pypi.org/project/pyxlsb/>`_ will be used.
  1235. .. versionadded:: 1.3.0
  1236. - Otherwise if `openpyxl <https://pypi.org/project/openpyxl/>`_ is installed,
  1237. then ``openpyxl`` will be used.
  1238. - Otherwise if ``xlrd >= 2.0`` is installed, a ``ValueError`` will be raised.
  1239. .. warning::
  1240. Please do not report issues when using ``xlrd`` to read ``.xlsx`` files.
  1241. This is not supported, switch to using ``openpyxl`` instead.
  1242. """
  1243. from pandas.io.excel._odfreader import ODFReader
  1244. from pandas.io.excel._openpyxl import OpenpyxlReader
  1245. from pandas.io.excel._pyxlsb import PyxlsbReader
  1246. from pandas.io.excel._xlrd import XlrdReader
  1247. _engines: Mapping[str, Any] = {
  1248. "xlrd": XlrdReader,
  1249. "openpyxl": OpenpyxlReader,
  1250. "odf": ODFReader,
  1251. "pyxlsb": PyxlsbReader,
  1252. }
  1253. def __init__(
  1254. self,
  1255. path_or_buffer,
  1256. engine: str | None = None,
  1257. storage_options: StorageOptions = None,
  1258. ) -> None:
  1259. if engine is not None and engine not in self._engines:
  1260. raise ValueError(f"Unknown engine: {engine}")
  1261. # First argument can also be bytes, so create a buffer
  1262. if isinstance(path_or_buffer, bytes):
  1263. path_or_buffer = BytesIO(path_or_buffer)
  1264. # Could be a str, ExcelFile, Book, etc.
  1265. self.io = path_or_buffer
  1266. # Always a string
  1267. self._io = stringify_path(path_or_buffer)
  1268. # Determine xlrd version if installed
  1269. if import_optional_dependency("xlrd", errors="ignore") is None:
  1270. xlrd_version = None
  1271. else:
  1272. import xlrd
  1273. xlrd_version = Version(get_version(xlrd))
  1274. if engine is None:
  1275. # Only determine ext if it is needed
  1276. ext: str | None
  1277. if xlrd_version is not None and isinstance(path_or_buffer, xlrd.Book):
  1278. ext = "xls"
  1279. else:
  1280. ext = inspect_excel_format(
  1281. content_or_path=path_or_buffer, storage_options=storage_options
  1282. )
  1283. if ext is None:
  1284. raise ValueError(
  1285. "Excel file format cannot be determined, you must specify "
  1286. "an engine manually."
  1287. )
  1288. engine = config.get_option(f"io.excel.{ext}.reader", silent=True)
  1289. if engine == "auto":
  1290. engine = get_default_engine(ext, mode="reader")
  1291. assert engine is not None
  1292. self.engine = engine
  1293. self.storage_options = storage_options
  1294. self._reader = self._engines[engine](self._io, storage_options=storage_options)
  1295. def __fspath__(self):
  1296. return self._io
  1297. def parse(
  1298. self,
  1299. sheet_name: str | int | list[int] | list[str] | None = 0,
  1300. header: int | Sequence[int] | None = 0,
  1301. names=None,
  1302. index_col: int | Sequence[int] | None = None,
  1303. usecols=None,
  1304. converters=None,
  1305. true_values: Iterable[Hashable] | None = None,
  1306. false_values: Iterable[Hashable] | None = None,
  1307. skiprows: Sequence[int] | int | Callable[[int], object] | None = None,
  1308. nrows: int | None = None,
  1309. na_values=None,
  1310. parse_dates: list | dict | bool = False,
  1311. date_parser: Callable | lib.NoDefault = lib.no_default,
  1312. date_format: str | dict[Hashable, str] | None = None,
  1313. thousands: str | None = None,
  1314. comment: str | None = None,
  1315. skipfooter: int = 0,
  1316. dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default,
  1317. **kwds,
  1318. ) -> DataFrame | dict[str, DataFrame] | dict[int, DataFrame]:
  1319. """
  1320. Parse specified sheet(s) into a DataFrame.
  1321. Equivalent to read_excel(ExcelFile, ...) See the read_excel
  1322. docstring for more info on accepted parameters.
  1323. Returns
  1324. -------
  1325. DataFrame or dict of DataFrames
  1326. DataFrame from the passed in Excel file.
  1327. """
  1328. return self._reader.parse(
  1329. sheet_name=sheet_name,
  1330. header=header,
  1331. names=names,
  1332. index_col=index_col,
  1333. usecols=usecols,
  1334. converters=converters,
  1335. true_values=true_values,
  1336. false_values=false_values,
  1337. skiprows=skiprows,
  1338. nrows=nrows,
  1339. na_values=na_values,
  1340. parse_dates=parse_dates,
  1341. date_parser=date_parser,
  1342. date_format=date_format,
  1343. thousands=thousands,
  1344. comment=comment,
  1345. skipfooter=skipfooter,
  1346. dtype_backend=dtype_backend,
  1347. **kwds,
  1348. )
  1349. @property
  1350. def book(self):
  1351. return self._reader.book
  1352. @property
  1353. def sheet_names(self):
  1354. return self._reader.sheet_names
  1355. def close(self) -> None:
  1356. """close io if necessary"""
  1357. self._reader.close()
  1358. def __enter__(self) -> ExcelFile:
  1359. return self
  1360. def __exit__(
  1361. self,
  1362. exc_type: type[BaseException] | None,
  1363. exc_value: BaseException | None,
  1364. traceback: TracebackType | None,
  1365. ) -> None:
  1366. self.close()