Python讀取和寫入Excel文件數據


前言

之前我們已經學過了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文件數據的操作,小伙們學會了嗎?


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM