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數據

總結:目前改變單元格的背景暫未實現(若有知道的,可以交流下,謝謝!)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章