zhangwuxuan

前言

之前我们已经学过了Python读取和写入txt,csv文件数据的操作,今天我们学习一下如何利用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 ,写入以下代码

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文件

以上就是利用Python代码读取和写入Excel文件数据的操作,小伙们学会了吗?

分类:

技术点:

相关文章: