使用技术:python3
使用库:xlrd,xlutils
注意点:因为使用xlrd + xlwt 边读边写入excel时,不能保留原excel中的样式,所以使用xlutils复制excel的方式,可以保留原来excel文件中的样式
代码如下:
#操作excel的测试代码
#使用python 读取txt文件的内容到excel中
import os
import re
import xlwt
#xlwt缺点 写入无法保留原格式
#如果要保留原格式可以通过xlutils库复制excel的方式写入
import xlrd
from xlutils.copy import copy
#txt文件中存储需要追加的内容,格式为 :
> 每行的第一列内容:值
filePath = "G:\\测试输入文件.txt"
xlsFile = "G:\\test2.xls"
#写入列中文 10 外文11
writeColIndex = 10
#首先读取txt文件中的内容中,填充到一个字典中
dict = {}
with open(filePath,'r',encoding='UTF-8') as f:
line = f.readline()
while line:
# 获取文件名
if (line is None or line.strip() == ''):
continue
# 取出文件名
docname = os.path.splitext(line.split(":")[0])[0].replace(" ","");
jilu = line.split(":")[1]
#取出 数值
s = re.sub("\D","",jilu)
dict[docname] = s
line = f.readline()
#1 打开excel文件 formatting_info= True 打开保留原excel格式
excel = xlrd.open_workbook(xlsFile,formatting_info=True)
readWorkSheet = excel.sheet_by_index(0)
#2 复制excel文件
copy_workBook = copy(excel)
#3 开始操作复制好的excel文件
#3.1 获取excel文件的第一个sheet页
ws = copy_workBook.get_sheet(0)
for rowIndex in range(readWorkSheet.nrows):
row = readWorkSheet.row_values(rowIndex) # 取出行的值;
if (rowIndex != 0):
title = row[0].replace(" ","")
if (title in dict.keys()):
ws.write(rowIndex, writeColIndex, dict[title])
#3 保存excel文件
copy_workBook.save("G:/test2.xls")
#注: xlrd模块0.8版本后不支持以xlsx为后缀名文件