Python实验二:openpyxl处理Excel数据

最近,应公司要求需要对Excel做批量复杂的数据处理,所有学习了下Python ,做了如下实验:

  • 如何通过数字转换成Excel相应的字母,如1=>,2=>B等,代码如下
#!/usr/bin/python3
# -*- coding:UTF-8 -*-
# Author:Victor
# Date:2019-11-05
# transfer_upper.py
def transfer(number=0):
    if number == 0:
        return False;
    # 目前最大列数为293,超出此数据,则无法判定
    if number > 293:
        return False;
    # 判断数据类型
    check_type = isinstance(number, int);
    if check_type == False:
        return False;
    up = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
          'V', 'W', 'X', 'Y', 'Z'];
    cols = ['A', 'B', 'C', 'D', 'E', 'F', 'E', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
            'U', 'V', 'W', 'X', 'Y', 'Z']
    first = ['A', 'B', 'C', 'D', 'E', 'F', 'E', 'G', 'H'];
    end = ['IA', 'IB', 'IC', 'ID', 'IE', 'IF', 'IE', 'IG', 'IH', 'II', 'IJ', 'IK', 'IL', 'IM', 'IN', 'IO', 'IP', 'IQ',
           'IR', 'IS', 'IT',
           'IU', 'IV'];
    for str in first:
        for color_val in cols:
            str_new = str + color_val;
            up.append(str_new);
    new_list = up + end;

    return new_list[number - 1];

  • 安装openpyxl : pip3 install openpyxl
    备注:目前只支持xlsx后缀名的数据
  • 测试源代码如下(准备好文件2.xlsx):
#!/usr/bin/python3
# -*- coding:UTF-8 -*-

import openpyxl;
from openpyxl.styles import colors;
from openpyxl.styles import Font;
from openpyxl.styles import NamedStyle;
from openpyxl.styles import Color;
from openpyxl.styles import PatternFill;
from transfer_upper import transfer;# 自定义开发

# 参考文献:https://openpyxl.readthedocs.io/en/stable/styles.html#cell-styles

commonBackgroundColorHex = "AACF91";
wb = openpyxl.load_workbook('E:/Python3Excute/2.xlsx');
# size:改变字体大小,color:改变字体颜色,bold:改变字体族系
fontObj1 = Font(size=12, color='4675C0', bold=True);
# 设置背景方法,确无法改变背景【原因:未知,暂不去深入研究】
patterFill = PatternFill(bgColor=Color(colors.RED));
# colorObj = Color(rgb='4675C0');
# sheet_names = wb.get_sheet_names();
#选取工作簿:方法一
sheet = wb.worksheets[0];  # 选取操作的工作簿
sheet2 = wb.worksheets[1];  # 第二个工作簿
# sheet(n) = wb.worksheets[n] #操作第n个工作簿(第二种工作方)
# 选取工作簿:方法二(比较直观点)
# sheet = wb.get_sheet_by_name('Sheet1');
# sheet2 = wb.get_sheet_by_name('Sheet2');

c = sheet['A1':'H8'];
total = [];
i = 1;
for op in c:
    str = [];
    j = 1;
    for cellObj in op:
    	#把对应的列表数字转换成字母,如:1->A
        str_up = transfer(j) + '%d' % i;
        # print(str_up);#A1,B1,C1.....
        sheet2[str_up].value = cellObj.value;  # 把Sheet1列表中的数据写入Sheet2

        sheet2[str_up].font = fontObj1;  # 设置字体大小
        sheet2[str_up].fill = patterFill;  # 改变背景样式
        # sheet2.color = colorObj;
        sheet2.row_dimensions[i].height = 30;  # 设置单元格宽和高
        sheet2.column_dimensions[transfer(j)].width = 20;  # 设置单元格宽和高

        str.append(cellObj.value);
        j += 1;
    # 处理等待输出的数据(仅供测试输出)
    total.append(str); # 列表尾部插入新的列表
    string = '|'.join(str);
    print(string);
    i += 1;
# 把上面的数据写入sheet2
# print(sheet2);
# print(sheet2['A1'].value);
wb.save('E:/Python3Excute/2.xlsx'); # 保存更新的Excel数据

总结:目前改变单元格的背景暂未实现(若有知道的,可以交流下,谢谢!)

发布了46 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/tangqing24680/article/details/102931066