U
    +ifZy                     @  sL  d Z ddlmZ ddlmZ ddlZddlZddlmZm	Z	m
Z
mZmZmZmZ ddlZddlZddlmZ ddlmZmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZm Z m!Z!m"Z" ddl#m$  m%Z& ddl'm(Z( ddl)m*Z* ddl+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1 G dd dZ2G dd de2Z3G dd dZ4G dd dZ5dS )zC
Utilities for conversion to writer-agnostic Excel representation.
    )annotations)reduceN)AnyCallableHashableIterableMappingSequencecast)is_list_like)
IndexLabelStorageOptions)doc)missing)is_float	is_scalar)	DataFrameIndex
MultiIndexPeriodIndex)_shared_docs)CSS4_COLORS)CSSResolver
CSSWarning)get_level_lengths)pprint_thingc                   @  s*   e Zd ZdZeZddddddddZdS )		ExcelCellrowcolvalstyle
mergestartmergeendNint
int | None)r   r   r"   r#   c                 C  s(   || _ || _|| _|| _|| _|| _d S Nr   )selfr   r   r    r!   r"   r#    r(   J/home/mars/bis/venv/lib/python3.8/site-packages/pandas/io/formats/excel.py__init__9   s    	zExcelCell.__init__)NNN)__name__
__module____qualname__Z
__fields__	__slots__r*   r(   r(   r(   r)   r   5   s      r   c                      s.   e Zd Zdddddddd fddZ  ZS )CssExcelCellr$   zdict | Nonez3dict[tuple[int, int], list[tuple[str, Any]]] | NoneCallable | None)r   r   r!   
css_stylescss_rowcss_colcss_converterc	                   sH   |r,|r,d dd |||f D }
||
}t jf ||||d|	S )N;c                 S  s    g | ]\}}|d  t | qS ):)str).0avr(   r(   r)   
<listcomp>Y   s     z)CssExcelCell.__init__.<locals>.<listcomp>r   r   r    r!   )joinsuperr*   )r'   r   r   r    r!   r1   r2   r3   r4   kwargscss	__class__r(   r)   r*   K   s    zCssExcelCell.__init__)r+   r,   r-   r*   __classcell__r(   r(   rA   r)   r/   J   s   r/   c                   @  s  e Zd ZU dZeZdddddddZddddddddddddddZdddd	Zd
ddddZ	de
d< d`ddddZe ZdddddZdddddZdddd d!Zdddd"d#Zdd$dd%d&Zdd'dd(d)Zddd*d+d,Zddd-d.d/Zdd0d1d2d3Zdd0d4d5d6Zdd7d8d9Zdd:dd;d<Zdd=dd>d?Zdd$dd@dAZdd$ddBdCZddDddEdFZdDddGdHdIZdd$ddJdKZddDddLdMZ ddNddOdPZ!dQdRdSdTZ"dddUdVdWZ#ddXdYdZd[Z$dddYd\d]Z%ddXdYd^d_Z&dS )aCSSToExcelConverteraK  
    A callable for converting CSS declarations to ExcelWriter styles

    Supports parts of CSS 2.2, with minimal CSS 3.0 support (e.g. text-shadow),
    focusing on font styling, backgrounds, borders and alignment.

    Operates by first computing CSS styles in a fairly generic
    way (see :meth:`compute_css`) then determining Excel style
    properties from CSS properties (see :meth:`build_xlstyle`).

    Parameters
    ----------
    inherited : str, optional
        CSS declarations understood to be the containing scope for the
        CSS processed by :meth:`__call__`.
    topcenterbottom)rE   ztext-topmiddleZbaselinerG   ztext-bottomTF)boldZbolderZ600Z700Z800Z900normalZlighter100Z200Z300Z400500)rJ   italicZoblique            )Zserifz
sans-serifZcursiveZfantasyzdict[str, str] | None	inheritedN
str | None)rR   c                 C  s    |d k	r|  || _nd | _d S r&   )compute_cssrR   )r'   rR   r(   r(   r)   r*      s    zCSSToExcelConverter.__init__r7   zdict[str, dict[str, str]])declarations_strreturnc                 C  s   |  || j}| |S )ax  
        Convert CSS declarations to ExcelWriter style.

        Parameters
        ----------
        declarations_str : str
            List of CSS declarations.
            e.g. "font-weight: bold; background: blue"

        Returns
        -------
        xlstyle : dict
            A style as interpreted by ExcelWriter when found in
            ExcelCell.style.
        )rT   rR   build_xlstyle)r'   rU   
propertiesr(   r(   r)   __call__   s    zCSSToExcelConverter.__call__zMapping[str, str])propsrV   c                   sN   |  || || || || |d}ddd fdd  | |S )N)	alignmentborderfillfontZnumber_formatzdict[str, str]None)drV   c                   sF   t |  D ]4\}}|dkr$| |= qt|tr | |s| |= qdS )z4Remove key where value is None, through nested dictsN)listitems
isinstancedict)r`   kr:   remove_noner(   r)   rg      s    
z6CSSToExcelConverter.build_xlstyle.<locals>.remove_none)build_alignmentbuild_border
build_fill
build_fontbuild_number_format)r'   rZ   outr(   rf   r)   rW      s    

z!CSSToExcelConverter.build_xlstylezdict[str, bool | str | None]c                 C  s   | d| || |dS )Nz
text-align)
horizontalvertical	wrap_text)get_get_vertical_alignment_get_is_wrap_textr'   rZ   r(   r(   r)   rh      s    z#CSSToExcelConverter.build_alignmentc                 C  s   | d}|r| j |S d S )Nzvertical-align)rq   VERTICAL_MAP)r'   rZ   Zvertical_alignr(   r(   r)   rr      s    
z+CSSToExcelConverter._get_vertical_alignmentzbool | Nonec                 C  s"   | dd krd S t|d dkS )Nzwhite-space)Znowrapprezpre-line)rq   boolrt   r(   r(   r)   rs      s    z%CSSToExcelConverter._get_is_wrap_textz dict[str, dict[str, str | None]]c                   s    fdddD S )Nc                   sP   i | ]H}|  d | d d | d d | ddqS )zborder-z-stylez-widthz-color)r!   color)_border_stylerq   color_to_excel)r8   ZsiderZ   r'   r(   r)   
<dictcomp>   s   z4CSSToExcelConverter.build_border.<locals>.<dictcomp>rE   rightrG   leftr(   rt   r(   r{   r)   ri      s    z CSSToExcelConverter.build_border)r!   widthc                 C  s   |d kr|d krd S |dks$|dkr(d S |  |}|d kr>d S |dkrJ|S |dkrVdS |dkrn|dkrjdS dS |dkr|dkrdS d	S d S )
NnoneZhidden)NZgrooveZridgeZinsetZoutsetsoliddoubleZdotted)ZhairthinZmediumDashDotDotZdashedZmediumDashed)_get_width_name)r'   r!   r   Z
width_namer(   r(   r)   ry      s&    
z!CSSToExcelConverter._border_style)width_inputrV   c                 C  s2   |  |}|dk rd S |dk r"dS |dk r.dS dS )Ngh㈵>g?r   gffffff@ZmediumZthick)_width_to_float)r'   r   r   r(   r(   r)   r     s    
z#CSSToExcelConverter._get_width_namefloat)r   rV   c                 C  s   |d krd}|  |S )NZ2pt)_pt_to_float)r'   r   r(   r(   r)   r   '  s    z#CSSToExcelConverter._width_to_float)	pt_stringrV   c                 C  s   | dstt|dS )Npt)endswithAssertionErrorr   rstrip)r'   r   r(   r(   r)   r   ,  s    z CSSToExcelConverter._pt_to_float)rZ   c                 C  s&   | d}|dkr"| |ddS d S )Nzbackground-color)Ntransparentr   r   )ZfgColorZpatternType)rq   rz   )r'   rZ   Z
fill_colorr(   r(   r)   rj   0  s    
zCSSToExcelConverter.build_fillzdict[str, str | None]c                 C  s,   | d}t|tr |ddn|}d|iS )Nznumber-format   §r5   Zformat_code)rq   rc   r7   replace)r'   rZ   fcr(   r(   r)   rl   7  s    
z'CSSToExcelConverter.build_number_formatz*dict[str, bool | int | float | str | None]c                 C  sv   |  |}| |}|r |d nd | || || || |d|krNdnd d|kpZd | |d| |d	S )Nr   	underlinesinglezline-throughrx   )	namefamilysizerI   rM   r   strikerx   Zshadow)	_get_font_names_get_decoration_select_font_family_get_font_size_get_is_bold_get_is_italicrz   rq   _get_shadow)r'   rZ   
font_names
decorationr(   r(   r)   rk   <  s    


zCSSToExcelConverter.build_fontc                 C  s   | d}|r| j |S d S )Nzfont-weight)rq   BOLD_MAP)r'   rZ   weightr(   r(   r)   r   N  s    
z CSSToExcelConverter._get_is_boldc                 C  s   | d}|r| j |S d S )Nz
font-style)rq   
ITALIC_MAP)r'   rZ   Z
font_styler(   r(   r)   r   T  s    
z"CSSToExcelConverter._get_is_italiczSequence[str]c                 C  s"   | d}|d k	r| S dS d S )Nztext-decorationr(   )rq   split)r'   rZ   r   r(   r(   r)   r   Z  s    
z#CSSToExcelConverter._get_decoration)r   rV   c                 C  s   d|krdS d S )Nr   r   r(   )r'   r   r(   r(   r)   _get_underlinea  s    z"CSSToExcelConverter._get_underlinec                 C  s    d|krt td|d S d S )Nztext-shadowz^[^#(]*[1-9])rw   researchrt   r(   r(   r)   r   f  s    zCSSToExcelConverter._get_shadowc                 C  s   t d|dd}g }|D ]f}|d d dkrF|dd dd}n.|d d dkrl|dd d	d}n| }|r|| q|S )
Nz(?x)
            (
            "(?:[^"]|\\")+"
            |
            '(?:[^']|\\')+'
            |
            [^'",]+
            )(?=,|\s*$)
        zfont-family rN   "z\"'z\')r   findallrq   r   stripappend)r'   rZ   Zfont_names_tmpr   r   r(   r(   r)   r   k  s    	
z#CSSToExcelConverter._get_font_nameszfloat | Nonec                 C  s    | d}|d kr|S | |S )Nz	font-size)rq   r   )r'   rZ   r   r(   r(   r)   r     s    
z"CSSToExcelConverter._get_font_sizer%   rV   c                 C  s&   d }|D ]}| j |}|r q"q|S r&   )
FAMILY_MAPrq   )r'   r   r   r   r(   r(   r)   r     s    z'CSSToExcelConverter._select_font_family)r    rV   c                 C  s\   |d krd S |  |r | |S z| j| W S  tk
rV   tdt| t Y nX d S )NzUnhandled color format: )_is_hex_color_convert_hex_to_excelNAMED_COLORSKeyErrorwarningswarnreprr   r'   r    r(   r(   r)   rz     s    

z"CSSToExcelConverter.color_to_excelrw   )color_stringrV   c                 C  s   t |dS )N#)rw   
startswith)r'   r   r(   r(   r)   r     s    z!CSSToExcelConverter._is_hex_colorc                 C  sH   | d}| |r<|d d |d d  |d d   S | S d S )Nr   r   rO   rN   )lstrip_is_shorthand_colorupperr'   r   coder(   r(   r)   r     s    

(z)CSSToExcelConverter._convert_hex_to_excelc                 C  s<   | d}t|dkrdS t|dkr*dS td| dS )zcCheck if color code is shorthand.

        #FFF is a shorthand as opposed to full #FFFFFF.
        r      T   FzUnexpected color N)r   len
ValueErrorr   r(   r(   r)   r     s    
z'CSSToExcelConverter._is_shorthand_color)N)'r+   r,   r-   __doc__r   r   ru   r   r   r   __annotations__r*   r   rT   rY   rW   rh   rr   rs   ri   ry   r   r   r   rj   rl   rk   r   r   r   r   r   r   r   r   rz   r   r   r   r(   r(   r(   r)   rD   `   sx   
'
	rD   c                   @  s   e Zd ZdZdZdZd4d	d
dddddd	dd	ddZedd Zdd Z	ddddZ
ddddZddddZdddd Zddd!d"Zddd#d$Zeddd%d&Zd'dd(d)d*Zddd+d,Zeed- d.d5d1d.d2d3ZdS )6ExcelFormattera9  
    Class for formatting a DataFrame to a list of ExcelCells,

    Parameters
    ----------
    df : DataFrame or Styler
    na_rep: na representation
    float_format : str, default None
        Format string for floating point numbers
    cols : sequence, optional
        Columns to write
    header : bool or sequence of str, default True
        Write out column names. If a list of string is given it is
        assumed to be aliases for the column names
    index : bool, default True
        output row names (index)
    index_label : str or sequence, default None
        Column label for index column(s) if desired. If None is given, and
        `header` and `index` are True, then the index names are used. A
        sequence should be given if the DataFrame uses MultiIndex.
    merge_cells : bool, default False
        Format MultiIndex and Hierarchical Rows as merged cells.
    inf_rep : str, default `'inf'`
        representation for np.inf values (which aren't representable in Excel)
        A `'-'` sign will be added in front of -inf.
    style_converter : callable, optional
        This translates Styler styles (CSS) into ExcelWriter styles.
        Defaults to ``CSSToExcelConverter()``.
        It should have signature css_declarations string -> excel style.
        This is only called for body cells.
    i   i @  r   NTFinfr7   rS   zSequence[Hashable] | NonezSequence[Hashable] | boolrw   zIndexLabel | Noner0   )	na_repfloat_formatcolsheaderindexindex_labelmerge_cellsinf_repstyle_converterc                 C  s   d| _ || _t|tsB|| _| j  |j}|
d kr:t }
|
| _nd | _d | _|| _	|d k	rt
t||jsxtdt
t||jt
t|krtd|j|d| _	| j	j| _|| _|| _|| _|| _|| _|	| _d S )Nr   z,passes columns are not ALL present dataframez.Not all names specified in 'columns' are found)columns)
rowcounterr   rc   r   stylerZ_computedatarD   r   dfr   r   intersectionr   r   setZreindexr   r   r   r   r   r   )r'   r   r   r   r   r   r   r   r   r   r   r(   r(   r)   r*     s2    

 
zExcelFormatter.__init__c                 C  s    ddidddddddddS )	NrI   Tr   r}   rF   rE   )rn   ro   )r^   Zbordersr[   r(   r'   r(   r(   r)   header_style  s    zExcelFormatter.header_stylec                 C  s   t |rt|r| j}nJt|rdt|r4| j}n0t|rLd| j }n| jd k	rdt	| j| }t
|dd d k	r|td|S )N-tzinfoz{Excel does not support datetimes with timezones. Please ensure that datetimes are timezone unaware before writing to Excel.)r   r   Zisnar   r   Zisposinf_scalarr   Zisneginf_scalarr   r   getattrr   r   r(   r(   r)   _format_value  s    


zExcelFormatter._format_valuezIterable[ExcelCell]r   c                 c  s  | j jdkr| jstd| js*| js*d S | j }|j| jddd}t|}d}d}| jrzt	| j
jtrzt| j
jd d }| jrHt|jD ]\}}t|||| jdV  qtt||j|jD ]\}\}}}	||	}
| D ]d\}}d\}}|dkr
||| |  }}t||| d |
| | jt| jdd ||| j||d	
V  qqnXtt| D ]J\}}
d
tt|
}t||| d || jt| jdd ||| jdV  qT|| _d S )NrN   z]Writing to Excel with MultiIndex columns and no index ('index'=False) is not yet implemented.FZsparsifyZadjoinnamesr   r<   NNctx_columns
r   r   r    r!   r1   r2   r3   r4   r"   r#   .r   r   r    r!   r1   r2   r3   r4   )r   Znlevelsr   NotImplementedError_has_aliasesr   formatr   r   rc   r   r   r   	enumerater   r   r   ziplevelscodestakerb   r/   r   r   r   r=   mapr   r   )r'   r   
level_strslevel_lengths	coloffsetlnumr   spansr   level_codesvaluesispan_valr"   r#   r:   r(   r(   r)   _format_header_mi*  sv      




z ExcelFormatter._format_header_mic                 c  s   | j s| jrd}| jr8d}t| jjtr8t| jjd }| j}| j rtt	| j| _t| jt| jkrt
dt| j dt| j dn| j}t|D ]6\}}t| j|| || jt| jdd d|| jdV  qd S )Nr   rN   zWriting z cols but got z aliasesr   r   )r   r   r   rc   r   r   r   r   r
   r	   r   r   r/   r   r   r   r   r   )r'   r   ZcolnamescolindexZcolnamer(   r(   r)   _format_header_regularo  s2    z%ExcelFormatter._format_header_regularc                   s   t  jtr  }n  }d} jjjrdd  jjjD dgt j  }t	dd t
dd |r fdd	t|D }  jd
7  _t||S )Nr(   c                 S  s   g | ]}|d k	r|ndqS Nr   r(   )r8   xr(   r(   r)   r;     s     z1ExcelFormatter._format_header.<locals>.<listcomp>r   c                 S  s   | o|S r&   r(   )r   yr(   r(   r)   <lambda>      z/ExcelFormatter._format_header.<locals>.<lambda>c                 S  s   | dkS r   r(   )r   r(   r(   r)   r     r   c                 3  s$   | ]\}}t  j|| jV  qd S r&   )r   r   r   )r8   r   r    r   r(   r)   	<genexpr>  s   z0ExcelFormatter._format_header.<locals>.<genexpr>rN   )rc   r   r   r   r   r   r   r   r   r   r   r   r   	itertoolschain)r'   genZgen2r   r(   r   r)   _format_header  s     


zExcelFormatter._format_headerc                 C  s"   t | jjtr|  S |  S d S r&   )rc   r   r   r   _format_hierarchical_rows_format_regular_rowsr   r(   r(   r)   _format_body  s    zExcelFormatter._format_bodyc                 c  s2  | j s| jr|  jd7  _| jr| jrJt| jtttj	t
frJ| jd }n(| jrdt| jtrd| j}n| jjjd }t| jtr|  jd7  _|r| jdk	rt| jd d|| jV  | jj}t| jjtr| jj }t|D ]6\}}t| j| d|| jt| jdd |d| jdV  qd}nd}| |E d H  d S )NrN   r   F	ctx_indexr   )r   r   r   r   r   rc   ra   tuplenpndarrayr   r7   r   r   r   r   r   r   r   Zto_timestampr   r/   r   r   r   _generate_body)r'   r   Zindex_valuesidxZidxvalr   r(   r(   r)   r    s@     

z#ExcelFormatter._format_regular_rowsc                 c  s  | j s| jr|  jd7  _d}| jr| jjj}| jrRt| jtt	t
jtfrR| j}t| jtrr| jrr|  jd7  _tj| r| jdk	rt|D ] \}}t| jd ||| jV  q| jr| jjjdddd}t|}t|| jjj| jjjD ]\}}}	|j|	|j|jd}
| D ]h\}}d\}}|dkrB| j| | d }|}t| j| ||
| | jt| j dd ||| j!||d	
V  q|d7 }qn^t| jj D ]P}t|D ]8\}}t| j| ||| jt| j dd ||| j!d
V  q|d7 }q| "|E d H  d S )NrN   r   FTr   )Z
allow_fillZ
fill_valuer   r	  r   r   )#r   r   r   r   r   r   r   rc   ra   r
  r  r  r   r   r   r   comZany_not_noner   r   r   r   r   r   r   r   r   Z_can_hold_naZ	_na_valuerb   r/   r   r   r   r  )r'   ZgcolidxZindex_labelsZcidxr   r   r   r   r   r   r   r   r   r"   r#   Zindexcolvalsr  Zindexcolvalr(   r(   r)   r    s    
     

z(ExcelFormatter._format_hierarchical_rowsc                 C  s
   t | jS )z1Whether the aliases for column names are present.)r   r   r   r(   r(   r)   r   )  s    zExcelFormatter._has_aliasesr$   )r   rV   c                 c  sn   t t| jD ]Z}| jjd d |f }t|D ]8\}}t| j| || |d t| j	dd ||| j
dV  q.qd S )Nctxr   )ranger   r   r   Zilocr   r/   r   r   r   r   )r'   r   ZcolidxZseriesr   r    r(   r(   r)   r  .  s    zExcelFormatter._generate_bodyc                 c  s2   t |  |  D ]}| |j|_|V  qd S r&   )r  r  r  r  r   r    )r'   cellr(   r(   r)   get_formatted_cells>  s    z"ExcelFormatter.get_formatted_cellsstorage_options)r  Sheet1r   r   c              	   C  s   ddl m} | jj\}	}
|	| jks,|
| jkrPtd|	 d|
 d| j d| j |  }t||rhd}n||||d}d}z|j
|||||d	 W 5 |r|	  X d
S )a#  
        writer : path-like, file-like, or ExcelWriter object
            File path or existing ExcelWriter
        sheet_name : str, default 'Sheet1'
            Name of sheet which will contain DataFrame
        startrow :
            upper left cell row to dump data frame
        startcol :
            upper left cell column to dump data frame
        freeze_panes : tuple of integer (length 2), default None
            Specifies the one-based bottommost row and rightmost column that
            is to be frozen
        engine : string, default None
            write engine to use if writer is a path - you can also set this
            via the options ``io.excel.xlsx.writer``, ``io.excel.xls.writer``,
            and ``io.excel.xlsm.writer``.

            .. deprecated:: 1.2.0

                As the `xlwt <https://pypi.org/project/xlwt/>`__ package is no longer
                maintained, the ``xlwt`` engine will be removed in a future
                version of pandas.

        {storage_options}

            .. versionadded:: 1.2.0
        r   )ExcelWriterz-This sheet is too large! Your sheet size is: z, z Max sheet size is: F)enginer  T)startrowstartcolfreeze_panesN)Zpandas.io.excelr  r   shapemax_rowsmax_colsr   r  rc   closeZwrite_cells)r'   writerZ
sheet_namer  r  r  r  r  r  Znum_rowsZnum_colsZformatted_cellsZ	need_saver(   r(   r)   writeC  s2    &
  
	zExcelFormatter.write)	r   NNTTNFr   N)r  r   r   NNN)r+   r,   r-   r   r  r  r*   propertyr   r   r   r   r  r  r  r  r   r  r  r   r   r   r(   r(   r(   r)   r     sD              .
E .Q      r   )6r   
__future__r   	functoolsr   r  r   typingr   r   r   r   r   r	   r
   r   numpyr  Zpandas._libs.libr   Zpandas._typingr   r   Zpandas.util._decoratorsr   Zpandas.core.dtypesr   Zpandas.core.dtypes.commonr   r   Zpandasr   r   r   r   Zpandas.core.commoncorecommonr  Zpandas.core.shared_docsr   Zpandas.io.formats._color_datar   Zpandas.io.formats.cssr   r   Zpandas.io.formats.formatr   Zpandas.io.formats.printingr   r   r/   rD   r   r(   r(   r(   r)   <module>   s2   $	  [