1. 程式人生 > >使用python讀取.txt檔案並儲存到Excel中

使用python讀取.txt檔案並儲存到Excel中

txt檔案中使用json格式儲存資料,使用Excel中的Workbook函式可以實現行中單元格的值輸入

worksheet.cell(r=i, c=j).value = file_cintent[str(i)][m]

student.txt:

{
	"1":["張三",150,120,100],
	"2":["李四",90,99,95],
	"3":["王五",60,66,68]
}
附上程式碼:
import json
from collections import OrderedDict
from openpyxl import Workbook

def txt_to_xlsx(filename):
    file = open(filename, 'r', encoding = 'UTF-8')
    file_cintent = json.load(file, encoding = 'UTF-8')
    print(file_cintent)
    workbook = Workbook()
    worksheet = workbook.worksheets[0]
    for i in range(1, len(file_cintent)+1):
        worksheet.cell(row = i, column = 1).value = i
        for m in range(0, len(file_cintent[str(i)])):
            print(file_cintent[str(i)])
            worksheet.cell(row = i, column = m+2).value = file_cintent[str(i)][m]
    workbook.save(filename = 'student.xls')

if __name__ == '__main__':
    txt_to_xlsx('student.txt')

輸出xls表格為: