Use Python to let Excel quickly filter data by conditions
This article uses python to quickly filter data in excel
There is a table of product sales for 12 months.
Features of the Python third-party library xlwings required for installation :
- xlwings can easily read and write data in Excel files, and can modify the cell format
- Can be seamlessly connected with Matplotlib and Pandas
- You can call a program written in VBA in an Excel file, or you can make VBA call a program written in Python
- Open source and free, always updated
Import xlwings:
import xlwings as xw
Launch Excel file via Python
- Open the Excel program
app =xw.App(visible=True,add_book=False)
Among them, the parameter visible (indicating whether the processing process is visible, that is, whether the process of processing Excel will be displayed), add_book (whether to open a new Excel program, that is, whether to open a new excel window).
- Open Excel file
workbook = app.books.open("2020 XX 公司销售表汇总表.xlsx")
- Get all forms
sheets_list = workbook.sheets
- Set filter criteria
select_value = '江西省'
select_value1 = '博士'
- New Sheet has filtered data
qxs_excel = workbook.sheets.add(select_value)
Custom Python traverse Excel function
- Create a new data list, add data to the list
range_value_list = []
- Custom single sheet data reading class
def readrange(excel):
for i in range(2,1000): #我的数据每张 Sheet 表最多只有 1000 行,所以设置的是 1000
#单个表格字符串
select_sheet_value = "E"+str(i)
select_sheet_value1 = "C"+str(i)
#整行表格字符串
str_sheet1 = "A"+str(i)+":"+"E"+str(i)
select_value_sheet = excel.range(select_sheet_value).value
select_value_sheet1 = excel.range(select_sheet_value1).value
if select_value_sheet == select_value and select_value_sheet1 == select_value1:#这里设置搜索条件判断,这里是表示两个筛选条件同时满足才会存入数据列表
str_value_row = excel.range(str_sheet1).value
range_value_list.append(str_value_row)
for excel in sheets_list:
readrange(excel)
Write the data into the new summary table
- Write header data first
qxs_excel.range("A1:F1").value = ["姓名","级别","学历","薪资","地址"]
- Cyclic write data list data to summary table
flag = 1 #因为计算机从 0 开始,0 行已经写入标题,所以这里是 1;如果有多行标题,根据实际情况设置
for i in range_value_list:
flag += 1
#整行表格字符串
str_sheet1 = "A"+str(flag)+":"+"E"+str(flag)
qxs_excel.range(str_sheet1).value = i
The effect after running is as follows: