美文网首页
Pandas Excel output set column w

Pandas Excel output set column w

作者: 万事皆成 | 来源:发表于2019-02-13 16:17 被阅读4次
    # Given a dict of dataframes, for example:
    # dfs = {'gadgets': df_gadgets, 'widgets': df_widgets}
    
    writer = pd.ExcelWriter(filename, engine='xlsxwriter')
    for sheetname, df in dfs.items():  # loop through `dict` of dataframes
        df.to_excel(writer, sheet_name=sheetname)  # send df to writer
        worksheet = writer.sheets[sheetname]  # pull worksheet object
        for idx, col in enumerate(df):  # loop through all columns
            series = df[col]
            max_len = max((
                series.astype(str).map(str_len).max(),  # len of largest item
                str_len(str(series.name))  # len of column name/header
                )) + 2  # adding a little extra space
            worksheet.set_column(idx, idx, max_len)  # set column width
    writer.save()
    

    一个中文utf8编码后是占3个字符,所以求长度的函数可以这样写

    def str_len(str):
        try:
            row_l=len(str)
            utf8_l=len(str.encode('utf-8'))
            return (utf8_l-row_l)/2+row_l
        except:
            return None
        return None
    

    Is there a way to auto-adjust Excel column widths with pandas.ExcelWriter?

    python包含中文字符串长度

    相关文章

      网友评论

          本文标题:Pandas Excel output set column w

          本文链接:https://www.haomeiwen.com/subject/fqrdeqtx.html