今天测试用机是红米note12 tubro
直接上代码,供大家借鉴参考。
def export_contact():
# 导出用户通讯录,导出的格式为特定的,最终转化为excel
cmd = "adb shell content query --uri content://contacts/phones/"
res = os.popen(cmd)
with os.popen(cmd) as fp: # 此处是在网上学的,用于解决编码问题。
bf = fp._stream.buffer.read()
try:
str = bf.decode().strip()
except UnicodeDecodeError:
str = bf.decode('gbk').strip()
# 对上面导出的数据进行处理,最终以excel的形式保存的电脑上。只要红米12下面测试过。
s = set()
ls = str.split('\n')
for li in ls:
ls1 = li.split(',') # 把ls中的每一行,又分隔成一个列表,最终把姓名和电话存储在集合(去重)中。
name = ls1[16].strip().replace("display_name=", "")
tel = ls1[1].strip().replace("number=", "")
s.add((name, tel))
# 保存在excel中
# 创建一个工作簿对象
workbook = openpyxl.Workbook()
# 选择一个工作表
sheet = workbook.active
r = 0
# 遍历字典,将数据写入工作表的单元格
for item in s:
r = r + 1
sheet.cell(row=r, column=1, value=item[0])
sheet.cell(row=r, column=2, value=item[1])
# 保存工作簿到文件
workbook.save('contanct.xlsx')