python實現文字與Excel內容相互轉換
阿新 • • 發佈:2019-01-07
思考:
如何用兩層迴圈將以下列表轉換為[‘1’, 1, 2, 3, ‘2’, 3, 4, 5]?
[('1',[1,2,3]),('2',[3,4,5])]
#解答在最後
正題
純文字檔案 student.txt為學生資訊, 裡面的內容如下所示:
{
"1":["張三",150,120,100],
"2":["李四",90,99,95],
"3":["王五",60,66,68]
}
請將以上內容轉換為表格形式如下:
import json
import xlwt,xlrd
from collections import OrderedDict
def txt_to_xls():
with open('student.txt') as f:
students_dict = json.load(f)
order_dict = sorted(students_dict.items(),key = lambda item:item[0])#對讀取的物件進行按鍵排序
wb = xlwt.Workbook() #建立一個工作簿
ws = wb.add_sheet('student') #建立一個sheet
row = 0
for k,v in order_dict:
ws.write(row,0 ,k)
col = 1
for item in v:
ws.write(row,col,item)
col += 1
row +=1
wb.save('student.xls') #儲存
if __name__=='__main__':
txt_to_xls()
將上邊cls表格中的資料匯出為json格式:
def xls_to_txt():
result = {}
workbook = xlrd.open_workbook('student.xls')
# 獲取所有sheet
#print workbook.sheet_names()
sheet1_name = workbook.sheet_names()[0]
# 根據sheet索引或者名稱獲取sheet內容
sheet1 = workbook.sheet_by_index(0) # sheet索引從0開始
# sheet的名稱,行數,列數
print sheet1.name
for i in range(sheet1.nrows):
result[sheet1.row_values(i)[0]] = sheet1.row_values(i)[1:]
for x in result:
for y in result[x]:
print y
with open('student.json','w') as fo:
json.dump(result,fo)
思考解答:
lst = []
for k, v in [('1',[1,2,3]),('2',[3,4,5])]:
lst.append(k)
for item in v:
lst.append(item)