Python操作Excel的四个工具包
- xlrd: 对Excel进行读相关操作,注意只能操作 .xls
- xlwt: 对Excel进行写相关操作,注意只能操作 .xls,且只能创建一个全新的Excel然后进行写入和保存。
- xlutils:对Excel进行读、写相关操作,注意只能操作 .xls
- openpyxl: 对Excel进行读、写相关操作,可操作 2010版的 .xlsx / .xlsm
工具包Python官网相关介绍文档
- xlrd: http://xlrd.readthedocs.io/en/latest/
- xlwt: http://xlwt.readthedocs.io/en/latest/
- xlutils: http://xlutils.readthedocs.io/en/latest/
- openpyxl: http://openpyxl.readthedocs.io/en/latest/
xlrd 简单使用
#!/usr/bin/env python #-*- coding:utf-8 -*- import xlrd import os def read_excel(line_num, table_name='Sheet1', excel_name='/FAQ.xls', excel_path='../../resource/): ''' @param line_num: 行/列索引 @param table_name: 表名 @param excel_name: Excel文件名 @param excel_path: Excel文件路径 @return : data 读取到的数据 ''' file_path = os.path.normpath(os.path.join(os.path.dirname(__file__), excel_path + excel_name )) with xlrd.open_workbook(file_path) as f: table = f.sheet_by_name(table_name) #nrows = table.nrows #遍历所有行 data = table.row_values(line_num) #读取行数据 #nrows = table.ncols #遍历所有列 #data = table.col_values(line_num) #读取列数据 return data
xlutils 简单使用
#!/usr/bin/env python #-*- coding:utf-8 -*- import xlrd import os from xlutils import copy def write_excel(row, col, data, sheet_index=0, excel_name='/FAQ.xls', excel_path='../../resource/): ''' @param row: 行索引 @param col: 列索引 @param data: 需写入的数据 @param sheet_index: 表索引 @param excel_name: Excel文件名 @param excel_path: Excel文件路径 @return : ''' file_path = os.path.normpath(os.path.join(os.path.dirname(__file__), excel_path + excel_name )) with xlrd.open_workbook(file_path, formatting_info=True) as wb: new_wb = copy(wb) new_sheet = new_wb.get_sheet(sheet_index) #设置单元格背景颜色0-Black,1=White,2=Red,3=Green,4=Blue,5=Yellow,6=Magenta style = 'pattern: pattern solid_pattern, pattern_fore_colour 3;' #设置单元格背景颜色 style += 'font: name arial;" #字体 style += 'alignment: horz CENTER, vert CENTER; ' #居中 style += ' borders: left DASHED, right DASHED, top DASHED, bottom DASHED' #边框 new_sheet.write(row, col, data, style ) #new_wb.save(file_path) #原Excel上修改和保存 new_wb.save(os.path.splitext(file_path)[0] + '.out' + os.path.splitext(file_path)[-1]) #保存新的Excel,输出为 FAQ.out.xls
来源:http://www.cnblogs.com/-brenda/p/8707627.html