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输出带颜色的字符串实例
Oct 10 Python
python实现生命游戏的示例代码(Game of Life)
Jan 24 Python
对python中执行DOS命令的3种方法总结
May 12 Python
python操作mysql代码总结
Jun 01 Python
Python语言快速上手学习方法
Dec 14 Python
我们为什么要减少Python中循环的使用
Jul 10 Python
python通过移动端访问查看电脑界面
Jan 06 Python
Python有参函数使用代码实例
Jan 06 Python
python词云库wordCloud使用方法详解(解决中文乱码)
Feb 17 Python
python怎么自定义捕获错误
Jun 29 Python
python实现每天自动签到领积分的示例代码
Aug 18 Python
Python 操作 MySQL数据库
Sep 18 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数据库操作面向对象的优点
2006/10/09 PHP
PHP使用NuSOAP调用Web服务的方法
2015/07/18 PHP
Zend Framework基于Command命令行建立ZF项目的方法
2017/02/18 PHP
JavaScript开发规范要求(规范化代码)
2010/08/16 Javascript
Javascript insertAfter() 实现函数代码
2011/10/12 Javascript
通过Javascript将数据导出到外部Excel文档的函数代码
2012/06/15 Javascript
简易js代码实现计算器操作
2013/04/15 Javascript
js去除空格的12种实用方法
2013/11/08 Javascript
javascript学习笔记(二)数组和对象部分
2014/09/30 Javascript
js制作简易年历完整实例
2015/01/28 Javascript
js选择器全面解析
2016/06/27 Javascript
JS+HTML5实现的前端购物车功能插件实例【附demo源码下载】
2016/10/17 Javascript
jQuery 表单序列化实例代码
2017/06/11 jQuery
Node.js 8 中的 util.promisify的详解
2017/06/12 Javascript
jquery操作ul的一些操作笔记整理(干货)
2017/08/31 jQuery
解决Vue打包上线之后部分CSS不生效的问题
2019/11/12 Javascript
Vue清除定时器setInterval优化方案分享
2020/07/21 Javascript
vue-cli3 热更新配置操作
2020/09/18 Javascript
vue项目中企业微信使用js-sdk时config和agentConfig配置方式详解
2020/12/15 Vue.js
[01:06:26]全国守擂赛第二周 Team Coach vs DeMonsTer
2020/04/28 DOTA
python分析apache访问日志脚本分享
2015/02/26 Python
Python3.x中自定义比较函数
2015/04/24 Python
python中正则表达式的使用方法
2018/02/25 Python
Python正则表达式和元字符详解
2018/11/29 Python
python分批定量读取文件内容,输出到不同文件中的方法
2018/12/08 Python
详解Python安装tesserocr遇到的各种问题及解决办法
2019/03/07 Python
Python调用shell命令常用方法(4种)
2020/05/11 Python
python 基于PYMYSQL使用MYSQL数据库
2020/12/24 Python
利用 CSS3 实现的无缝轮播功能代码
2017/09/25 HTML / CSS
HTML5 Video标签的属性、方法和事件汇总介绍
2015/04/24 HTML / CSS
Net-A-Porter美国官网:全球时尚奢侈品名站
2017/02/11 全球购物
澳大利亚百货公司:David Jones
2018/02/08 全球购物
Reformation官网:美国女装品牌
2018/09/14 全球购物
BudgetAir印度:预订航班、酒店和汽车租赁
2019/07/07 全球购物
煤矿安全生产月活动总结
2014/07/05 职场文书
MySQL触发器的使用
2021/05/24 MySQL