如何將txt文本導入excel實例
這里我們用python中的random.randint方法在txt文本當中隨機生成100份成績
這里我的項目文件名為to_score.py
import random
#隨機寫入100個學生的數學,計算機分數到txt文本當中
with open("score.txt","w") as fw:
num_s = 1
num_e = 100
for i in range(num_s,num_e+1):
#遍歷1-100隨機生成100份成績
math = random.randint(10,100)
computer = random.randint(10,100)
#\n是換行符,若有不會使用format方法的請自行查詢!
fw.write("{},{},{}\n".format(i,math,computer))
#若with open as 放在這個位置,則read出來的是null值
#因為read()讀取時是從指針位置開始讀取的.所以這里一邊寫入數據一邊讀取數據,讀取出來的只有空值.
with open(r"score.txt","r") as fr :
print(fr.read())#read()讀取文檔全部內容,查看是否寫入
以上操作完成之后,你會發現你的項目當中會多出一個score.txt.
這就是隨機生成的100份成績
接下來我們新創建一個sheet.py(名字隨意)
導入openpyxl包.
利用相關的方法把txt文本導入excel表格
from openpyxl import Workbook
#導入openpyxl包
wb = Workbook()#創建一個excel
sheet = wb.active#獲取當前excel的sheet
datas = None#定義一個空值,接收score.txt的參數
with open("score.txt","r") as fr :#讀取上面txt的數據,這里我的txt文本命名為score.txt
datas = fr.readlines()
sheet["A1"] = "學號" #excel中:A列第一行,寫入"學號"
sheet["B1"] = "數學"
sheet["C1"] = "計算機"
for i in range(len(datas)):#遍歷datas的長度,100行
id_,math_,computer_ = datas[i].split(",")
"""
當i等於1時這里的 id_,math,computer=(to_execl.py里的)i,math,computer
以此類推
"""
row = str(i + 2)
sheet["A" + row] = id_
sheet["B" + row] = math_
sheet["C" + row] = computer_
wb.save("score.xlsx") #保存excel名字隨意,后綴要注意
這樣我們完成了對txt導入excel的相關操作.