python操作openpyxl导出Excel 设置单元格格式及合并处理代码实例


Posted in Python onAugust 27, 2019

这篇文章主要介绍了python操作openpyxl导出Excel 设置单元格格式及合并处理代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

贴上一个例子,里面设计很多用法,根据将相同日期的某些行合并处理。

from openpyxl import Workbook                                                                 
from openpyxl.styles import Font, Fill, Alignment, Border, Side, PatternFill                                         
from handlers.boss_accountant import PbOrderManageBase                                                    
from handlers.base.pub_func import ConfigFunc                                                         
from dal.models import Shop                                                                  
from dal.db_configs import DBSession                                                             
def export_excel(filename, sheetname, content_body):                                                     
  """                                                                            
  Excel表格导出                                                                         
  :param filename: 表格名称                                                                   
  :param sheetname: 工作表名称                                                                  
  :param content_body: 内容体                                                                 
  :return: None                                                                       
  """                                                                            
  workbook = Workbook()                                                                   
                                                                               
  if not filename:                                                                     
    filename = "导出表格.xlsx"                                                                
                                                                               
  workbook_sheet = workbook.active                                                             
  if not sheetname:                                                                     
    sheetname = "工作表"                                                                   
  workbook_sheet.title = sheetname                                                             
                                                                               
  merge_dict, sheet_row_len, sheet_column_len = merge_content(content_body)                                         
  print(merge_dict)                                                                     
  # 数据写入                                                                          
  for row in content_body:                                                                 
    workbook_sheet.append(row)                                                              
                                                                               
  # 合并处理                                                                          
  for key in merge_dict.keys():                                                               
    merge_data = merge_dict.get(key)                                                           
    if key == "title":                                                                  
      workbook_sheet.merge_cells(start_row=merge_data[0], start_column=merge_data[1],                                  
                    end_row=merge_data[2], end_column=merge_data[3])                                    
      workbook_sheet.merge_cells(start_row=2, start_column=merge_data[1],                                        
                    end_row=2, end_column=merge_data[3])                                          
      workbook_sheet['A1'].font = Font(size=20, bold=True)                                               
      workbook_sheet['A1'].alignment = Alignment(horizontal='center', vertical='center')                                
    else:                                                                         
      # 使用sum求值                                                                     
      workbook_sheet.cell(row=merge_data[0] + 3, column=12).value = '=SUM({}:{})'.format(                                
        format_value(str(merge_data[0] + 3), 10), format_value(str(merge_data[1] + 3), 10))                              
      workbook_sheet.cell(row=merge_data[0] + 3, column=14).value = '=SUM({}:{})'.format(                                
        format_value(str(merge_data[0] + 3), 11), format_value(str(merge_data[1] + 3), 11))                              
      workbook_sheet.cell(row=merge_data[0] + 3, column=13).value = '=({}-{})'.format(                                 
        format_value(str(merge_data[0] + 3), 12), format_value(str(merge_data[0] + 3), 14))                              
                                                                               
      for i in [2,12, 13, 14]:                                                             
        workbook_sheet.merge_cells(start_row=merge_data[0]+3, start_column=i,                                     
                      end_row=merge_data[1]+3, end_column=i)                                       
  # 合计求和                                                                          
  for i in [12, 13, 14]:                                                                  
    workbook_sheet.cell(row=sheet_row_len, column=i).value = '=SUM({}:{})'.format(                                    
      format_value(3, i), format_value(sheet_row_len - 1, i))                                              
                                                                               
  # 单元格底色                                                                          
  last_row = workbook_sheet[sheet_row_len]                                                         
  for each_cell in last_row:                                                                
    each_cell.fill = PatternFill("solid", fgColor="00CDCD")                                                
                                                                               
  # 边框设置                                                                          
  for each_common_row in workbook_sheet.iter_rows("A1:{}".format(format_value(sheet_row_len, sheet_column_len))):                      
    for each_cell in each_common_row:                                                           
      each_cell.border = Border(left=Side(style='thin', color='000000'),                                        
                   right=Side(style='thin', color='000000'),                                        
                   top=Side(style='thin', color='000000'),                                         
                   bottom=Side(style='thin', color='000000')                                        
                   )                                                            
  workbook_sheet.column_dimensions['B'].width = 15                                                     
  workbook_sheet.column_dimensions['C'].width = 20                                                     
  workbook.save(filename)                                                                  
def merge_content(content_body):                                                               
  """                                                                            
  合并统计                                                                           
  :param content_body: 数据体                                                                 
  :return: 合并字典                                                                       
  """                                                                            
  sheet_column_len = len(content_body[3])                                                          
  sheet_row_len = len(content_body)                                                             
  merge_dict = {}                                                                      
  data_content = content_body[3:-1]                                                             
  merge_dict["title"] = (1, 1, 1, sheet_column_len)                                                     
  current_data = data_content[0][1]                                                             
  current_row = 0                                                                      
  start_row = 1                                                                       
  end_row = 0                                                                        
  for data in data_content:                                                                 
    current_row += 1                                                                   
    x = data[1]                                                                      
    if data[1] == current_data:                                                              
      merge_dict[data[1]] = (start_row, current_row)                                                  
    else:                                                                         
      merge_dict[data[1]] = (current_row, current_row)                                                 
      current_data = data[1]                                                              
                                                                               
      start_row = current_row                                                              
                                                                               
  return merge_dict, sheet_row_len, sheet_column_len                                                    
def format_value(row, column):                                                                
  """数字转ABC                                                                         
  """                                                                            
  change_dict = {                                                                      
    1: "A", 2: "B", 3: "C", 4: "D", 5: "E", 6: "F", 7: "G", 8: "H", 9: "I", 10: "J",                                   
    11: "K", 12: "L", 13: "M", 14: "N", 15: "O", 16: "P", 17: "Q", 18: "R", 19: "S", 20: "T",                               
    21: "U", 22: "V", 23: "W", 24: "X", 25: "Y", 26: "Z",                                                 
  }                                                                             
  column = change_dict.get(column)                                                             
  return str(column)+str(row)                                                                
                                                                               
def export_func_new(args, session, shop_id):                                                         
  # check_time = 0                                                                     
  # debtor_id = 2884                                                                    
  # debtor_name: 肖小菜                                                                    
  # end_date:                                                                        
  # start_date: 2019 - 07                                                                  
  # statistic_date: 3                                                                    
  # data_type: 1                                                                      
  data_content = []                                                                     
  check_time = 0                                                                      
  from_date = "2019-07"                                                                   
  to_date = ""                                                                       
  debtor_name = "肖小菜"                                                                                                                                                   
  if_success, query_data, *_ = PbOrderManageBase.common_get_credit_stream(args, session, shop_id, export=True,                       
                                      need_sum=False, check_time=check_time                       
  )                                                                             
  if not if_success:                                                                    
    raise ValueError(query_data)                                                             
  fee_text = ConfigFunc.get_fee_text(session, shop_id)                                                   
  get_weight_unit_text = ConfigFunc.get_weight_unit_text(session, shop_id)                                         
                                                                               
  # 表店铺、客户名称                                                                        
  shop_name = session.query(Shop.shop_name).filter_by(id=shop_id).first()                                          
  data_content.append([shop_name[0]])                                                            
  data_content.append(["客户:{}".format(debtor_name)])                                                    
  # 表头                                                                           
  fee_text_total = '{}小计'.format(fee_text)                                                         
  header_content = [                                                                    
    "序号", "日期", "货品名", "数量", "重量/{}".format(get_weight_unit_text), "单价", "货品小记", "押金小计", fee_text_total,                         
    "赊账金额","待还款", "赊账小记", "已还款", "待还款小计"                                                         
  ]                                                                             
  file_name_begin = "客户还款"                                                                 
  data_content.append(header_content)                                                            
  # 还款数据                                                                          
  index_num = 0                                                                       
  for single_data in query_data:                                                              
    index_num += 1                                                                    
    sales_time = single_data.get("sales_time", "")                                                    
    if sales_time:                                                                    
      sales_time = sales_time.split(" ")[0]                                                                                                                                      
    _payback_money = single_data["unpayback_money"]                                                    
    single_content = [index_num,                                                             
             sales_time,                                                             
             single_data["only_goods_name"],                                                   
             single_data["commission_mul"],                                                   
             single_data["sales_num"],                                                      
             "%s元/%s" % (single_data["fact_price"],                                               
                   single_data["goods_unit"]),                                               
             single_data["goods_total"],                                                     
             single_data["commission_mul"],                                                   
             single_data["deposit_total"],                                                    
             single_data["credit_cent"],                                                     
             _payback_money,                                                           
             0,                                                                 
             0,                                                                 
             0]                                                                 
    data_content.append(single_content)                                                          
  # 表尾合计                                                                          
  data_content.append(["合计"])                                                                
  config = ConfigFunc.get_config(session, shop_id)                                                     
  if not config.enable_deposit:                                                               
    index_deposit_total = data_content[0].index("押金小计")                                                  
    for data in data_content:                                                               
      data.pop(index_deposit_total)                                                           
                                                                               
  if not config.enable_commission:                                                             
    index_commission_total = data_content[0].index(fee_text_total)                                            
    for data in data_content:                                                               
      data.pop(index_commission_total)                                                         
                                                                               
  file_name = "{}流水记录导出_{}~{}.xlsx".format(file_name_begin, from_date, to_date)                                       
  return file_name, data_content                                                              
                                                                               
if __name__ == "__main__":                                                                  
  filename = "测试打印表格.xlsx"                                                                 
  sheetname = "工作表2"                                                                                                                                                                                                                                  
  session = DBSession()                                                                   
  args = {                                                                         
    "check_time": 0,                                                                   
    "debtor_id": 2884,                                                                  
    "debtor_name": "肖小菜",                                                                 
    "start_date": "2019-07",                                                               
    "statistic_date": 3,                                                                 
    "data_type": 1                                                                    
  }                                                                             
  filename, content_body = export_func_new(args, session, 104)                                                                                                                                                                                                             
  # filename = "测试打印表格.xlsx"                                                                
  # sheetname = "工作表2"                                                                   
  # content_body = []                                                                    
  # content_body.append(["打印表格表头"])                                                             
  # content_body.append(["客户:肖某某"])                                                             
  # content_body.append(["日期", "货品销售", "自营销售", "代卖销售", "联营销售", "总价"])                                            
  # content_body.append(["1", "2", "3.1", "4.1", "5.1", "5.1"])                                              
  # content_body.append(["1", "2", "3.1", "4.1", "5.1", "5.1"])                                               
  # content_body.append(["1", "2", "3.1", "4.1", "5.1", "5.1"])

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python的动态重新封装的教程
Apr 11 Python
Python压缩解压缩zip文件及破解zip文件密码的方法
Nov 04 Python
Python实现的矩阵类实例
Aug 22 Python
Python基于identicon库创建类似Github上用的头像功能
Sep 25 Python
Python探索之静态方法和类方法的区别详解
Oct 27 Python
在python tkinter中Canvas实现进度条显示的方法
Jun 14 Python
python字典setdefault方法和get方法使用实例
Dec 25 Python
django项目中新增app的2种实现方法
Apr 01 Python
python批量处理多DNS多域名的nslookup解析实现
Jun 28 Python
python实现批处理文件
Jul 28 Python
Python Process创建进程的2种方法详解
Jan 25 Python
TensorFlow中tf.batch_matmul()的用法
Jun 02 Python
Python使用get_text()方法从大段html中提取文本的实例
Aug 27 #Python
简单易懂Pytorch实战实例VGG深度网络
Aug 27 #Python
selenium+PhantomJS爬取豆瓣读书
Aug 26 #Python
python多任务之协程的使用详解
Aug 26 #Python
python数组循环处理方法
Aug 26 #Python
python中利用numpy.array()实现俩个数值列表的对应相加方法
Aug 26 #Python
关于Python中的向量相加和numpy中的向量相加效率对比
Aug 26 #Python
You might like
用PHP将数据导入到Foxmail
2006/10/09 PHP
解析Win7 XAMPP apache无法启动的问题
2013/06/26 PHP
PHP基于双向链表与排序操作实现的会员排名功能示例
2017/12/26 PHP
Laravel5.1 框架响应基本用法实例分析
2020/01/04 PHP
Jquery easyui 下loaing效果示例代码
2013/08/12 Javascript
Jquery实现的tab效果可以指定默认显示第几页
2013/10/16 Javascript
深入理解JS中的变量及作用域、undefined与null
2014/03/04 Javascript
ExtJS 刷新后如何默认选中刷新前最后一次选中的节点
2014/04/03 Javascript
js 判断各种数据类型的简单方法(推荐)
2016/08/29 Javascript
jQuery flip插件实现的翻牌效果示例【附demo源码下载】
2016/09/20 Javascript
浅谈Nodejs中的作用域问题
2016/12/26 NodeJs
jQuery实现对象转为url参数的方法
2017/01/11 Javascript
jquery中封装函数传递当前元素的方法示例
2017/05/05 jQuery
浅谈angular.js跨域post解决方案
2017/08/30 Javascript
关于angularJs清除浏览器缓存的方法
2017/11/28 Javascript
在vue项目中安装使用Mint-UI的方法
2017/12/27 Javascript
使用vuex存储用户信息到localStorage的实例
2019/11/11 Javascript
Node登录权限验证token验证实现的方法示例
2020/05/25 Javascript
[01:32]TI珍贵瞬间系列(一)
2020/08/26 DOTA
python实现批量改文件名称的方法
2015/05/25 Python
Python查询阿里巴巴关键字排名的方法
2015/07/08 Python
python3 发送任意文件邮件的实例
2018/01/23 Python
Pycharm设置去除显示的波浪线方法
2018/10/28 Python
PyQT5 QTableView显示绑定数据的实例详解
2019/06/25 Python
python多进程并行代码实例
2019/09/30 Python
女子锻炼服装和瑜伽服装:Splits59
2019/03/04 全球购物
艺术系应届生的自我评价
2013/10/19 职场文书
咖啡店的创业计划书,让你hold不住
2014/01/03 职场文书
药品促销活动方案
2014/02/14 职场文书
安全生产目标责任书
2014/04/14 职场文书
优秀学生干部事迹材料
2014/12/24 职场文书
胡雪岩故居导游词
2015/02/06 职场文书
村官个人总结范文
2015/03/03 职场文书
2015年会计人员工作总结
2015/05/22 职场文书
如何在向量化NumPy数组上进行移动窗口
2021/05/18 Python
Java生成读取条形码和二维码的简单示例
2021/07/09 Java/Android