1 安装xlrd模块
pip install xlrd
2 读取Excel
# -*- coding: utf-8 -*-
import xlrd
import os,shutil
def open_excel(file= 'file.xls'):
try:
data = xlrd.open_workbook(file)
return data
except Exception,e:
print str(e)
def mycopyfile(srcfile,dstfile):
if not os.path.isfile(srcfile):
print "%s not exist!"%(srcfile)
else:
fpath,fname=os.path.split(dstfile) #分离文件名和路径
if not os.path.exists(fpath):
os.makedirs(fpath) #创建路径
shutil.copyfile(srcfile,dstfile) #复制文件
print "copy %s -> %s"%( srcfile,dstfile)
dst='D:\\temp\\'
mycopyfile(srcfile,dstfile)
file_paths = data
for p in file_paths:
srcfile = p
dstfile = dst + p.splt('/')[-1]
mycopyfile(srcfile,dstfile)
需要用到os.work()函数,xlwt模块,找出路径,然后把路径直接写入即可,os.work遍历找出,文件多的话速度上会比较慢。
有个类似例程,仅供你参考:
使用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表格为: