用python帮忙写一个读取xlsx文档,批量查询手机号归属地中文显示,并生成新的文档
时间: 2024-03-14 07:43:08 浏览: 16
可以使用openpyxl库来读取xlsx文档,使用上面提供的函数`get_phone_location()`来查询手机号归属地,并使用openpyxl库将结果写入新的文档。具体代码如下:
```python
import openpyxl
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font
from get_phone_location import get_phone_location
# 打开原始xlsx文件和新建的xlsx文件
wb = openpyxl.load_workbook('原始文件.xlsx')
new_wb = openpyxl.Workbook()
# 遍历原始文件中的所有sheet
for sheet_name in wb.sheetnames:
sheet = wb[sheet_name]
new_sheet = new_wb.create_sheet(sheet_name)
# 遍历原始文件中的所有行和列
for row in sheet.iter_rows():
for cell in row:
column_letter = get_column_letter(cell.column)
target_cell = new_sheet[f"{column_letter}{cell.row}"]
if cell.value and isinstance(cell.value, str) and cell.value.isdigit():
# 查询手机号归属地
result = get_phone_location(cell.value)
target_cell.value = result
# 设置字体为中文
target_cell.font = Font(name='Microsoft YaHei')
else:
target_cell.value = cell.value
# 保存新的xlsx文件
new_wb.save('新文件.xlsx')
```
其中,`wb`为原始xlsx文件,`new_wb`为新建的xlsx文件。遍历原始文件中的所有sheet,并在新的xlsx文件中新建对应的sheet。遍历原始文件中的所有行和列,查询手机号归属地并将结果写入新的xlsx文件中,同时将字体设置为中文。最后保存新的xlsx文件即可。
注意:此代码仅供学习交流使用,请勿用于非法用途。