python调用xlwings读取excel 按指定三列的内容对行进行分类 并将分类的结果保存到不同的表格中
时间: 2024-02-06 09:10:43 浏览: 22
可以按照以下步骤实现:
1. 导入 `xlwings` 模块并打开 Excel 文件。
```python
import xlwings as xw
wb = xw.Book('example.xlsx')
```
2. 选择需要操作的工作表。
```python
sht = wb.sheets['Sheet1']
```
3. 读取指定三列的内容,将其存储为列表。
```python
col1 = sht.range('A2:A100').value # 第一列
col2 = sht.range('B2:B100').value # 第二列
col3 = sht.range('C2:C100').value # 第三列
```
4. 根据指定条件对行进行分类,并将分类的结果存储到不同的表格中。
```python
# 定义分类条件
cond1 = 'A'
cond2 = 'B'
# 初始化分类结果
result1 = []
result2 = []
# 遍历每一行数据,根据条件进行分类
for i in range(len(col1)):
if col1[i] == cond1 and col2[i] == cond2:
result1.append([col1[i], col2[i], col3[i]])
else:
result2.append([col1[i], col2[i], col3[i]])
# 将分类结果写入不同的表格
sht1 = wb.sheets.add(name='Result1')
sht1.range('A1').value = [['Col1', 'Col2', 'Col3']] + result1
sht2 = wb.sheets.add(name='Result2')
sht2.range('A1').value = [['Col1', 'Col2', 'Col3']] + result2
```
5. 关闭 Excel 文件。
```python
wb.close()
```
完整代码如下:
```python
import xlwings as xw
# 打开 Excel 文件
wb = xw.Book('example.xlsx')
# 选择需要操作的工作表
sht = wb.sheets['Sheet1']
# 读取指定三列的内容
col1 = sht.range('A2:A100').value # 第一列
col2 = sht.range('B2:B100').value # 第二列
col3 = sht.range('C2:C100').value # 第三列
# 根据指定条件对行进行分类,并将分类的结果存储到不同的表格中
cond1 = 'A'
cond2 = 'B'
result1 = []
result2 = []
for i in range(len(col1)):
if col1[i] == cond1 and col2[i] == cond2:
result1.append([col1[i], col2[i], col3[i]])
else:
result2.append([col1[i], col2[i], col3[i]])
sht1 = wb.sheets.add(name='Result1')
sht1.range('A1').value = [['Col1', 'Col2', 'Col3']] + result1
sht2 = wb.sheets.add(name='Result2')
sht2.range('A1').value = [['Col1', 'Col2', 'Col3']] + result2
# 关闭 Excel 文件
wb.close()
```