专题02-python操作excel文件案例

笔者是一个痴迷于挖掘数据中的价值的学习人,希望在平日的工作学习中,挖掘数据的价值,找寻数据的秘密,笔者认为,数据的价值不仅仅只体现在企业中,个人也可以体会到数据的魅力,用技术力量探索行为密码,让大数据助跑每一个人,欢迎直筒们关注我的公众号,大家一起讨论数据中的那些有趣的事情。

我的公众号为:livandata

       主要也是最近用到excel比较频繁,感觉以后也会经常使用,而且网上看到的内容多以单独某一个功能为主,没有一个比较系统完整的案例,来将常用的excel知识做汇总,本文主要基于这样的思考,汇总出一个平时用到的案例,这一版的代码没有做精简化处理,主要是实现了相应的功能,如果有兴趣,可以将这些代码在进行二次处理即可。

        本文的案例场景为:通过openpyxl的包生成一个自带格式的excel文件,修改其文件名称、sheet名称、字体、颜色、合并单元格、边框等功能,最终汇总成一个基本的表格样式。

        原以为通过这样的方式可以简化excel制表的过程,但是写代码的过程中才发现,有些南辕北辙了,一个表格搞了大半天,后来想到了一个折中的方法,就是首先用excel制作好一个内容格式,然后利用openpyxl包将这个文件复制100份,感觉效率更高一点,本文将这两个方法代码都贴出来,供大家参考,主要也是为了方便后期找代码时能及时的找到这里。

代码位置为:https://github.com/livan123/model_test

1、纯代码生成excel的表格:

#!/usr/bin/env python
# _*_ UTF-8 _*_
import openpyxl
import os
from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.chart import BarChart, Series, Reference, BarChart3D
from openpyxl.styles import Color, Font, Alignment
from openpyxl.styles import Border, Side
from openpyxl.styles.colors import BLUE, RED, GREEN, YELLOW
from openpyxl.styles import PatternFill

def create_excel(context_list,title_list,sheet_list):
    # 1、创建excel文件
    f = openpyxl.Workbook()
    for i in range(int(sheet_list[0])):
        f.create_sheet(title=sheet_list[i+1], index=i)
    # 2、创建sheet格式
    # sheet:
    sheet = f.worksheets[2]
    for i in range(0,5):
        # 行合并
        sheet.merge_cells(start_row=16*i+3, start_column=2, end_row=16*i+18, end_column=2)
        sheet.merge_cells(start_row=16*i+3, start_column=3, end_row=16*i+6, end_column=3)
        sheet.merge_cells(start_row=16*i+7, start_column=3, end_row=16*i+10, end_column=3)
        sheet.merge_cells(start_row=16*i+11, start_column=3, end_row=16*i+14, end_column=3)
        sheet.merge_cells(start_row=16*i+15, start_column=3, end_row=16*i+18, end_column=3)
        sheet.merge_cells(start_row=16*i+3, start_column=4, end_row=16*i+6, end_column=4)
        sheet.merge_cells(start_row=16*i+7, start_column=4, end_row=16*i+10, end_column=4)
        sheet.merge_cells(start_row=16*i+11, start_column=4, end_row=16*i+14, end_column=4)
        sheet.merge_cells(start_row=16*i+15, start_column=4, end_row=16*i+18, end_column=4)
    sheet.merge_cells(start_row=83, start_column=2, end_row=83, end_column=4)
    sheet.merge_cells(start_row=84, start_column=2, end_row=84, end_column=4)
    sheet.merge_cells(start_row=85, start_column=2, end_row=85, end_column=4)

    # 设置单元格字体
    font = Font(name=u'宋体', size=9, bold=True)
    font2 = Font(name=u'宋体', size=9)
    sheet.cell(row=1, column=i+1).font = font
    # 格式
    align = Alignment(horizontal='center', vertical='center')
    fill = PatternFill(start_color='CC99CC', end_color='CC99CC', fill_type='solid')
    fill2 = PatternFill(start_color='CCCCCC', end_color='CCCCCC', fill_type='solid')
    sheet.freeze_panes = 'F3'
    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'))

    for i in range(2,86):
        for j in range(2,37):
            sheet.cell(row=i, column=j).border = border

    for i in range(0,20):
        for j in range(5,37):
            sheet.cell(row=4*i+6, column=j).fill = fill2

    # 3、填写内容
    for i in range(len(context_list)):
        sheet.cell(row=2, column=i+2).alignment = align
        sheet.cell(row=2, column=i+2, value=10).fill = fill
        sheet.cell(row=2, column=i+2).font = font
        sheet.cell(row=2, column=i+2).value = context_list[i]

    B_list = ['一', '二', '三', '四', '五']
    sheet.cell(row=3, column=2).alignment = align
    sheet.cell(row=3, column=2).font = font
    sheet.cell(row=3, column=2).value = B_list[0]
    sheet.cell(row=19, column=2).alignment = align
    sheet.cell(row=19, column=2).font = font
    sheet.cell(row=19, column=2).value = B_list[1]
    sheet.cell(row=35, column=2).alignment = align
    sheet.cell(row=35, column=2).font = font
    sheet.cell(row=35, column=2).value = B_list[2]
    sheet.cell(row=51, column=2).alignment = align
    sheet.cell(row=51, column=2).font = font
    sheet.cell(row=51, column=2).value = B_list[3]
    sheet.cell(row=67, column=2).alignment = align
    sheet.cell(row=67, column=2).font = font
    sheet.cell(row=67, column=2).value = B_list[4]

    C_list = ['一个月', '两个月', '三个月', '四个月']
    for j in range(len(C_list)):
        sheet.cell(row=3+4*j, column=3).alignment = align
        sheet.cell(row=3+4*j, column=3).font = font
        sheet.cell(row=3+4*j, column=3).value = C_list[j]
        sheet.cell(row=19+4*j, column=3).alignment = align
        sheet.cell(row=19+4*j, column=3).font = font
        sheet.cell(row=19+4*j, column=3).value = C_list[j]
        sheet.cell(row=35+4*j, column=3).alignment = align
        sheet.cell(row=35+4*j, column=3).font = font
        sheet.cell(row=35+4*j, column=3).value = C_list[j]
        sheet.cell(row=51+4*j, column=3).alignment = align
        sheet.cell(row=51+4*j, column=3).font = font
        sheet.cell(row=51+4*j, column=3).value = C_list[j]
        sheet.cell(row=67+4*j, column=3).alignment = align
        sheet.cell(row=67+4*j, column=3).font = font
        sheet.cell(row=67+4*j, column=3).value = C_list[j]

    D_list = ["1签约","2签约","3交付","/","1签约",
              "2签约","3交付","/","1签约","2签约",
              "3交付","/","1签约","2签约","3交付",
              "/","1签约","2签约","3交付","/"]
    for i in range(len(D_list)):
        sheet.cell(row=4*i+3, column=4).alignment = align
        sheet.cell(row=4 * i + 3, column=4).font = font
        sheet.cell(row=4*i+3, column=4).value = D_list[i]

    E_list=['叶1','叶2','叶3','叶4']
    for t in range(len(E_list)):
        for l in range(0,20):
            sheet.cell(row=t + (4*l+3), column=5).alignment = align
            sheet.cell(row=t + (4 * l + 3), column=5).font = font2
            sheet.cell(row=t + (4*l+3), column=5).value = E_list[t]

    row_list = ["成绩","分数","百分比"]
    sheet.cell(row=83, column=2).alignment = align
    sheet.cell(row=83, column=2).font = font
    sheet.cell(row=83, column=2).value = row_list[0]
    sheet.cell(row=84, column=2).alignment = align
    sheet.cell(row=84, column=2).font = font
    sheet.cell(row=84, column=2).value = row_list[1]
    sheet.cell(row=85, column=2).alignment = align
    sheet.cell(row=85, column=2).font = font
    sheet.cell(row=85, column=2).value = row_list[2]

    # 4、为模板添加公式
    sheet["A1"] = "=SUM(A2, B1)"

    # 5、保存文件
    curPath = os.getcwd()
    tempPath = 'file_target'
    targetPath = curPath + os.path.sep + tempPath
    if not os.path.exists(targetPath):
        os.makedirs(targetPath)
    for i in range(len(title_list)):
        f.save(targetPath+"/"+title_list[i]+".xlsx")

if __name__ == '__main__':
    context_list = ["季度","期别","对象","案例","合计","项目1","项目2",
                    "项目3","项目4","项目5","项目6","项目7","项目8","项目9",
                    "项目10","项目11","项目12","项目13","项目14","项目15",
                    "项目16","项目17","项目18","项目19","项目20","项目21",
                    "项目22","项目23","项目24","项目25","项目26","项目27",
                    "项目28","项目29","项目30",]
    title_list = ['2018XXXXXX']
    sheet_list = ['4','说明','合计','案例','sheet3']
    create_excel(context_list,title_list,sheet_list)

2、先在excel中完成格式,然后用python复制100份:

#!/usr/bin/env python
# _*_ UTF-8 _*_
'''
@project:copy-excel
@author:xiaofei
'''
import os
import os.path
import shutil

def copyFileto(sourcefile, title_list):
    # 创建相对路径的文件夹
    curPath = os.getcwd()
    tempPath = 'file_target'
    targetPath = curPath + os.path.sep + tempPath
    if not os.path.exists(targetPath):
        os.makedirs(targetPath)
    # 复制文件
    for i in range(len(title_list)):
        target = targetPath + "/" + title_list[i] + ".xlsx"
        shutil.copy(sourcefile, target)

if __name__ == '__main__':
    sourcefile = 'C:/Users/XXX/Desktop/2019.xlsx'
    title_list = ['2000XXXXXXXXX','2001XXXXXXXXX','2002XXXXXXXXX','2003XXXXXXXXX'
                ,'2004XXXXXXXXX','2005XXXXXXXXX','2006XXXXXXXXX','2007XXXXXXXXX'
                ,'2008XXXXXXXXX','2009XXXXXXXXX','2010XXXXXXXXX','2011XXXXXXXXX'
                ,'2012XXXXXXXXX','2013XXXXXXXXX','2014XXXXXXXXX']
    copyFileto(sourcefile,title_list)

        个人以为,代码本身的作用是为了提高效率,是用最少的时间完成最多的工作,如果在写代码的过程中发现增加了工作量,就应该适当的调整一下方法了,有些重复性的工作可以通过局部的代码化完成简单高效的转变,就像上面的两段代码,第一段花费了大半天的时间,但是第二段代码反而只消耗“excel制作时间+一分钟左右代码写作的时间”,相对于第一种方法便提高了一定的效率,通过此案例,也想产生一些思考,怎么样才能提高效率,往往最高效的是组合的方法,而不是独守一种方法,一种原则,希望在以后的工作中能找到更多更高效的工作方式。

发布了137 篇原创文章 · 获赞 93 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/livan1234/article/details/86527334