Python Automated Office-openpyxl creates an Excel to write data automatically storage

The previous article on automated office introduced some basic commands for the openpyxl module to process Excel files, but the operation commands involved in the article are not very complete, so this article is here; introduce an example from creating a Workbook to storing it on a local disk , The operation commands involved will be more comprehensive, and the content is summarized as follows:

  • Create a new Workbook and save it;

  • Create a new sheet, modify the title and tabColor;

  • Assign values ​​to the cells in the sheet;

  • Delete the specified row and column in the sheet (multiple rows and multiple columns);

  • Insert the specified row and column in the sheet (multiple rows and multiple columns);

  • Add a filtering mechanism to the specified column in the sheet;

  • Merge unit rows;

  • Set the cell font style, filling style, and alignment style;

  • Use function commands in Excel spreadsheets;

1. Create a new Excel file (Workbook)

from openpyxl import Workbook
from openpyxl.utils import get_column_letter

wb = Workbook()
dest_filename = "Empty_book.xlsx"
wb.save(dest_filename)

Snipaste_2020-10-03_15-30-46.jpg

2. Change the title of the sheet

ws1 = wb.active
ws1.title = 'range names'

Snipaste_2020-10-03_09-36-35.jpg

**3, fill data in 40*600 cells of the first sheet**

for row in range(1,40):
    ws1.append(range(600))

Snipaste_2020-10-03_09-53-30.jpg

4. Apply the sum function formula

openpyxl also has a powerful function, you can use the built-in functions of the Excel table; the function syntax is basically the same as that in Excel, you need to add a line of code to the import module to import the FORMULAE module before use

from openpyxl.utils import FORMULAE

Use the SUM function to find the sum of the values ​​of each row and column, and create a new column for storage

for row in range(1,40):
    ws1["WC{}".format(row)] = '=SUM(A{}:WB{})'.format(row,row)

Snipaste_2020-10-03_15-32-43.jpg

5. Add a filtering mechanism to the first row of the table

Prior to joining screening mechanism requires special attention to the specified range of cells used auto_filterin the module refparameters

ws1.auto_filter.ref = "A1:WC39"

Then modify the specified column to be filtered. Here I have added a filtering module to each column in the table;

for row in range(600):
    ws1.auto_filter.add_filter_column(row,vals = ['1','25'])#对每一列加入过滤机制

In the add_filter_column() function, row is used to specify the index of the column to be added. For example, 0 is the first column, and the following vals have not been found useful yet.

Snipaste_2020-10-03_15-33-31.jpg

In addition, let’s talk about it. It seems that the add_sort_condition module in the openpyxl package does not seem to be of any use. Still in disorder

ws1.auto_filter.ref = "A1:WC39"

for row in range(600):
    ws1.auto_filter.add_filter_column(row,vals = ['1','25'])#对每一列加入过滤机制

for i in range(2,40):
    ws1['A{}'.format(i)] = random.choice(range(50))# 更改第一列数据

ws1.auto_filter.add_sort_condition("WC2:WC35") # 对Excel 第一列进行排序

SUM.jpg

6, insert rows and columns

Insert row method

  • insert_rows(idx,amount),
    • Insert before the specified row idx, amount indicates the number of rows to be inserted, the default is 1;

Insert column method

  • insert_cols(idx,amount)
    • Insert before the specified column, amount represents the number of columns to be inserted, the default is 1;
# 插入行和列

ws1.insert_rows(2,amount = 2) #在第二行前面加入两空行
ws1.insert_cols(2,amount = 3) # 在第二列前面加入三个空列

Snipaste_2020-10-03_11-24-23.jpg

7. Delete rows and columns (multiple rows or single row)

Delete column method

  • delete_cols(idx,amount)
    • The deletion starts with the column index idx, and the amount indicates the number of deleted columns;
  • delete_rows(idx,amount)
    • The deletion starts with the row index idx, and the amount represents the number of deleted rows;
# 删除行与列

ws1.delete_cols(2,amount = 3) # 删除 第 2 列为起始索引,共3列
ws1.delete_rows(4,amount = 5) # 删除 第 4 行为起始索引,共5行

hanglie.jpg

8, merge lines

  • merge_cells(range_string,start_row,start_column,end_row,end_column)
    • range_string, indicates the range of cells to be merged, such as "A2:F3", you only need to set this parameter when merging;
    • start_row, the starting row, for example, start_row = 2;
    • end_row, stop the row, for example, end_row = 3;
    • start_column, starting column, start_column = 1;
    • end_column, end column, end_column = 5;
ws1.merge_cells(range_string = "A2:F3") # 合并多个单元格,A2-F3

# ws1.merge_cells(start_row=2, start_column=1, end_row=3, end_column=5) # 与上面效果等价;

merge.jpg

9. Set the cell style

Font style settings, here you need to use the Font function in the openpyxl.styles.fonts module,

9.1 , font style setting, Font() function module is used

Application font styles, to set a good Font () style assigned 单元格.fontattributes can be, as follows

from openpyxl.styles import colors, Font, Fill, NamedStyle
from openpyxl.styles import PatternFill, Border, Side, Alignment

ws1['A2'].font = Font(bold = True,color ='FFB6C1',sz = 15.0,i = True,outline = True)

Snipaste_2020-10-03_15-56-19.jpg

9.2, to set the alignment, you need to use the Alignment function in the openpyxl.styles.alignment module

When the application is similar to the way the font, then create Alignment method, assign 单元格.alignmentto the following format

ws1['A2'].alignment = Alignment(horizontal = 'centerContinuous',shrinkToFit = True,textRotation = 20,vertical = 'bottom',wrapText = True)

align.jpg

9.3 . Set the filling style. The openpyxl.styles.fills module provides two commonly used filling methods, GrdaientFill -> Gradient Fill and PatternFill -> Pattern Fill;

Application, create a GradientFill () or PatternFill () method, after the parameters are set, assign 单元格.fillto

ws1['A2'].fill = PatternFill(bgColor ='DC143C',fill_type = 'solid')

Snipaste_2020-10-03_15-13-46.jpg

**10, create a new sheet **

**10.1, **Create a new sheet, modify the title, specify the cell, and tabColor;

ws2 = wb.create_sheet(title = "Pi")
ws2['F5'] = 3.14 # 
ws2.sheet_properties.tabColor = "FF0000" # 修改颜色

Snipaste_2020-10-03_15-15-36.jpg

10.2, create a new sheet, assign values ​​to cells in the range of rows 10-20 and columns 27-54 (column names are sufficient)

Snipaste_2020-10-03_15-16-24.jpg

ws3 = wb.create_sheet(title = "Data")
for row in range(10,20):
    for col in range(27,54):
        _ = ws3.cell(column = col,row =row,value = "{0}".format(get_column_letter(col)))

11. Excel save

Finally, move the department and store the modified Excel table in the specified location

wb.save(filename = dest_filename)

The complete code in the case is posted below, and those who need it are picked up by themselves

from openpyxl import Workbook
from openpyxl.utils import get_column_letter
from openpyxl.utils import FORMULAE
import random

wb =  Workbook()
dest_filename = "Empty_book.xlsx"
ws1 = wb.active
ws1.title = 'range names'


# 对第一个 sheet 操作
for row in range(1,40):
    ws1.append(range(600))
for row in range(1,40):
    ws1["WC{}".format(row)] = '=SUM(A{}:WB{})'.format(row,row)
    
ws1.auto_filter.ref = "A1:WC39"

for row in range(600):
    ws1.auto_filter.add_filter_column(row,vals = ['1','25'])#对每一列加入过滤机制

for i in range(2,40):
    ws1['A{}'.format(i)] = random.choice(range(50))# 更改第一列数据

ws1.auto_filter.add_sort_condition("WC2:WC35") # 对Excel 第一列进行排序


# 插入行和列
ws1.insert_rows(2,amount = 2) #在第二行前面加入两空行
ws1.insert_cols(2,amount = 3) # 在第二列前面加入三个空列


# 删除行与列
ws1.delete_cols(2,amount = 3) # 删除 第 2 列,3列
ws1.delete_rows(4,amount = 5) # 删除 第 4 行,5行


# 合并单元格
ws1.merge_cells(range_string = "A2:F3") # 合并多个单元格,A2-F3
# ws1.merge_cells(start_row=2, start_column=1, end_row=3, end_column=5) # 与上面效果等价;

from openpyxl.styles import colors, Font, Fill, NamedStyle
from openpyxl.styles import PatternFill, Border, Side, Alignment

ws1['A2'] = '合并后标题'
ws1['A2'].font = Font(bold = True,color ='FFB6C1',sz = 15.0,i = True,outline = True)

# 单元格对其设置
ws1['A2'].alignment = Alignment(horizontal = 'centerContinuous',shrinkToFit = True,textRotation = 20,vertical = 'bottom',wrapText = True)


# 单元格填充颜色设置
ws1['A2'].fill = PatternFill(bgColor ='DC143C',fill_type = 'solid')

# 对第二个 sheet 操作
ws2 = wb.create_sheet(title = "Pi")
ws2['F5'] = 3.14 # 
ws2.sheet_properties.tabColor = "FF0000" # 修改颜色

# 对第三个 sheet 操作
ws3 = wb.create_sheet(title = "Data")
for row in range(10,20):
    for col in range(27,54):
        _ = ws3.cell(column = col,row =row,value = "{0}".format(get_column_letter(col)))
        
# 保存Excel 表格
wb.save(dest_filename)

The above is all the content of this article, and thank you all for reading!

Guess you like

Origin blog.csdn.net/weixin_42512684/article/details/109264302