Python读取和写入Excel文件数据

一:Python读取Excel文件数据。

(1)创建Excel数据文件,创建好文件记得要关闭文件,不然读取不了文件内容.

在这里插入图片描述
(2)打开PyCharm,,创建python file ,写入以下代码

#读取xls文件,一定要把xlsx后缀改成xls
import xlrd
file_name = xlrd.open_workbook('G:\\info.xls')#得到文件
table =file_name.sheets()[0]#得到sheet页
nrows = table.nrows #总行数
ncols = table.ncols #总列数
i = 0
while i < nrows:
    cell = table.row_values(i)[1] #得到数字列数据
    ctype = table.cell(i, 1).ctype #得到数字列数据的格式
    username=table.row_values(i)[0]
    if ctype == 2 and cell % 1 == 0: #判断是否是纯数字
     password= int(cell)  #是纯数字就转化位int类型
     print('用户名:%s'%username,'密码:%s'%password)
    i=i+1

(3)运行后的结果如下
在这里插入图片描述
二:Python写入Excel文件数据。

(1)打开PyCharm,,创建python file ,写入以下代码

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import random
import string
import csv
import xlrd
import xlwt
#注意这里的 excel 文件的后缀是 xls 如果是 xlsx 打开是会提示无效,新建excel表格后要选择文本格式保存
all_str = string.ascii_letters + string.digits
excelpath =('G:\\user.xls')  #新建excel文件
workbook = xlwt.Workbook(encoding='utf-8')  #写入excel文件
sheet = workbook.add_sheet('Sheet1',cell_overwrite_ok=True)  #新增一个sheet工作表
headlist=[u'账号',u'密码',u'邮箱']   #写入数据头
row=0
col=0
for head in headlist:
    sheet.write(row,col,head)
    col=col+1
for i in range(1,4):#写入3行数据
    for j in range(1,3):#写入3列数据
        username = ''.join(random.sample(all_str, 5))+'#$%'
        # password = random.randint(100000, 999999) 生成随机数
        password= ''.join(random.sample(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'z', 'y', 'x', 'w)', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o',
            'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'],8))
        Email=''.join(random.sample(all_str, 5))+'@163.com'
        sheet.write(i,j-1,username)
        sheet.write(i,j,password)
        sheet.write(i,j,Email)
        # sheet.write(i-1, j-1, username)   没有写标题时数据从第一行开始写入
        # sheet.write(i-1, j, password)
    workbook.save(excelpath) #保存
    print(u"生成第[%d]个账号"%(i))

(2)运行后的结果如下
在这里插入图片描述
生成Excel文件
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/sinat_38682860/article/details/108868609