https://github.com/Yixiaohan/show-me-the-code
纯文本文件 student.txt为学生信息, 里面的内容(包括花括号)如下所示:
{
“1”:[“张三”,150,120,100],
“2”:[“李四”,90,99,95],
“3”:[“王五”,60,66,68]
}
请将上述内容写到 student.xls 文件中,如下图所示:
openpyxl库可以用来读写2010版本的excel,所以用这个库。
代码很简单,附上openpyxl的官方文档网址:http://openpyxl.readthedocs.org
Talk is cheap, show you my code.
#! /usr/bin/env python
#! -*- coding: utf-8 -*-
__author__ = 'Sophie'
from openpyxl import Workbook
from openpyxl.styles import Alignment,Font,colors
import re
wb = Workbook()
dest_file = '/Users/Sophie/PycharmProjects/PythonPractice/PythonPractice_0014/student.xlsx'
ws = wb.create_sheet(title = 'student')
alignment = Alignment(horizontal='center', vertical='center')
font = Font(bold=True,color=colors.BLUE)
col = 'ABCDE'
ws[col[0]+'1'] = '#'
ws[col[1]+'1'] = '姓名'
ws[col[2]+'1'] = '数学'
ws[col[3]+'1'] = '英语'
ws[col[4]+'1'] = '语文'
for x in col:
ws[x+'1'].alignment = alignment
ws[x+'1'].font = font
data = []
p = re.compile(':\[')
source_file = open('/Users/Sophie/PycharmProjects/PythonPractice/PythonPractice_0014/student.txt','r')
for line in source_file:
if not line.startswith('{') and not line.startswith('}'):
line = line.strip('\n], ')
line = p.sub(',',line)
data.append(line.split(','))
#print data
source_file.close()
for i in range(len(data)):
for j in range(5):
ws[col[j]+str(i+2)] = data[i][j].strip('"')
ws[col[j]+str(i+2)].alignment = alignment
wb.save(dest_file)
附上student.txt和student.xlsx