您的位置:首页 > 编程语言 > Python开发

Python中xlrd、xlwt、win32com模块对xls文件的读写操作

2015-08-11 17:25 731 查看
这篇文章是接上一篇  
Python对Excel的操作实践总结 

这个是处理一些xls的日志文件的部分代码(将多个文件的错误日志整理到一个文件中),不一定能运行,仅供参考部分读写操作。

# -*- coding: utf-8 -*-
#xlrd和xlwt只支持xls文件读写,openpyxl只支持xlsx文件的读写操作
import xlrd
import xlwt
import win32com
from win32com.client import constants,Dispatch
from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.writer.excel import ExcelWriter

#--------------------------------使用win32com模块批量读入要处理的log文件--------------#
#注意表的计数是从1开始的和openpyxl类似
def win32ReadExcel(inputFile,num):
#存放数据字典
data_dic = {}
line = 0
for i in range(1,num+1):
readfile = inputFile + str(i) + '.xls'
print (readfile)
xlApp = win32com.client.Dispatch('Excel.Application')
wb = xlApp.Workbooks.Open(readfile)

#取第一张表
ws = wb.Worksheets(1)
info = ws.UsedRange
rows = info.Rows.Count
print (rows)
# 建立存储数据的字典
# t = ws.Cells(1, 1).Value
# print (t)
for rx in range(0,rows-1):
temp_list = []

w1 = ws.Cells(rx+2, 1).Value
w2 = ws.Cells(rx+2, 2).Value
w3 = ws.Cells(rx+2, 3).Value
w4 = ws.Cells(rx+2, 4).Value
w5 = ws.Cells(rx+2, 5).Value
temp_list = [w1,w2,w3,w4,w5]
data_dic[line] = temp_list
line = line + 1
# for i in range(rows):

# 	data_dic[line] = ws.Rows[i+1].Cells
# 	line = line + 1
print (data_dic)
return data_dic

#------------------------------使用xlrd模块批量读入要处理的log文件--------------#
def readExcel(inputFile,num):
#存放数据字典
data_dic = {}
line = 0
for i in range(1,num+1):
readfile = inputFile + str(i) + '.xls'
print (readfile)
wb = xlrd.open_workbook(readfile)

#取第一张表
ws = wb.sheets()[0]
rows = ws.nrows
print (rows)
# 建立存储数据的字典
for rx in range(0,rows-1):
# print (rx)
data_dic[line] = ws.row_values(rx+1)
line = line + 1
return data_dic

#-------------------------生成的xls格式的错误日志信息---------------------#
#注意xls格式的表示从0开始计数的
def exportXlsExcel(outputFile,data_log):
file = xlwt.Workbook(encoding='utf-8',style_compression=0)
table = file.add_sheet('sheet1',cell_overwrite_ok=True)
table.write(0,0,'1')
table.write(0,1,'2')
table.write(0,2,'3')
table.write(0,3,'4')
table.write(0,4,'5')
#读取过滤后的日志信息并写入xls文件中
for i in range(0,len(data_log)):
for j in range(0,5):
table.write(i+1,j,data_log[i][j])

file.save(outputFile);

#---------------------------------程序入口---------------------------------#
if __name__ == '__main__':
data_dic = {}
data_dic = win32ReadExcel('H:\Practice\j730_5_',3)
#data_log = dealLog(data_dic)
#exportXlsxExcel('bbbb3.xlsx',data_log)
exportXlsExcel('bbbb.xls',data_log)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: