python用workbook类方法带格式保存excel
Excel中,Ctrl+Shift+Enter在单元格中输入公式,Ctrl+S保存文档 #生活技巧# #数码产品使用技巧# #办公软件快捷键#
主要步骤:
1.用add_worksheet添加一个新的工作表,sheetname为工作表名称2.用add_format在工作表中创建一个新的格式对象来格式化单元格3.用set_row和set_column方法设置sheet表单元格的行高和列宽4.用write方法将普通数据写入单元格中本例是直接将现有数据存到excel为例的
def change_format(self,df, writer, Item):"""修改dataframe的数据格式,如小数转为%,日期改成%Y-%m-%d"""df.to_excel(writer, sheet_name=Item, index=False)workbook = writer.bookworksheet = writer.sheets[Item]cell_fmt = {'bold': False, 'font_name': '微软雅黑', 'font_size': 8, 'align': 'center', 'valign': 'vcenter', 'border': 0,'text_wrap':True}header_fmt = {'bold': True, 'font_name': '微软雅黑', 'font_size': 6, 'align': 'center', 'valign': 'vcenter', 'border': 0, 'bg_color': '#808080','text_wrap':True}cell_format = workbook.add_format(cell_fmt)header_format = workbook.add_format(header_fmt)df_col = [each for each in df.columns if each not in ['date', 'cus_type', '活跃人数','ad_channel','当日游客数','当日设备数']]# format 部分列进行%和保留两位小数处理if '比例' in list(df.iloc[:,0]): for i in range(row_num,df.shape[0]): for j in df_col: try: if float(df.loc[i,j])<=1: df.loc[i, j] = str(df.loc[i, j]*100)[:4]+ '%' print(df.loc[i, j]) except Exception as ExceptionError: print('format % 每日新增数据格式处理 比例异常',ExceptionError) passelif '人均' in list(df.iloc[:,0]): for i in range(row_num,df.shape[0]): for j in df_col: try: df.loc[i, j] = np.round(df.loc[i, j],2) except Exception as ExceptionError: print('format % 每日新增数据格式处理 人均异常',ExceptionError) passelse: pass#format datetimefor k in range(df.shape[0]): try: df.iloc[k,0] = pd.to_datetime(df.iloc[k,0]).strftime("%Y-%m-%d") except Exception as ExceptionError: print('时间格式处理异常:', str(ExceptionError)) pass# 列标题单元格格式处理# for colx, value in enumerate(df.columns.values):# worksheet.write(0, colx, value, header_format)# worksheet.write(row_num+1, colx, value, header_format)# A:C列宽16,D:Z列宽8,并全部按照cell_format格式处理worksheet.set_column('A:C', 16, cell_format)worksheet.set_column('D:Z', 8, cell_format)df.to_excel(writer, sheet_name=Item, index=False)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051网址:python用workbook类方法带格式保存excel https://www.yuejiaxmz.com/news/view/93544
相关内容
纯前端表格开发控件SpreadJS:类Excel,功能涵盖Excel的 95% 以上轻松解除Excel只读模式的几种实用方法
Excel表格混乱?教你几招整理绝招(excel表格添乱怎么整理)
EXCEL电子表格使用技巧大全
python
excel 计算文本型数学表达式 用 evaluate
多个Excel内容合并技巧:一键复制到单个单元格(多个excel内容复制到一个单元格)
Excel中SUMIF函数如何使用
工作中常用的25个Excel操作技巧,附详细步骤,收藏备用
excel怎么做思维导图?轻松掌握你的想法和项目