笔者小白在最近的qq记录分析的任务中需要用到对excel的操作,在这里做一个总结。
这里需要指出的是这篇文章总结了
如何利用xlwt新建一个excel文件,如何利用xlrd只读一个excel文件。
在文章的末尾总结了如何读取一个已经存在的execel文件,然后再进行修改的方法。
一、读excel表
读excel要用到xlrd模块,官网参考 http://pypi.python.org/pypi/xlrd
安装方法:pip install xlrd
然后就可以跟着里面的例子稍微试一下就知道怎么用了。大概的流程是这样的:
1、导入模块
import xlrd
2、打开Excel文件读取数据
data = xlrd.open_workbook('excel.xls')
3、获取一个工作表
table = data.sheets()[0] #通过索引顺序获取
table = data.sheet_by_index(0) #通过索引顺序获取
table = data.sheet_by_name(u'Sheet1') #通过名称获取
4、获取整行和整列的值(返回数组)
table.row_values(i)
table.col_values(i)
5、获取行数和列数
table.nrows
table.ncols
6、获取单元格
table.cell(0,0).value
table.cell(2,3).value
二、写excel表
写excel表要用到xlwt模块,官网参考 http://pypi.python.org/pypi/xlwt
安装方法:pip install xlwt
大致使用流程如下:
1、导入模块
import xlwt
2、创建workbook(其实就是excel,后来保存一下就行)
workbook = xlwt.Workbook(encoding = 'ascii')
3、创建表
worksheet = workbook.add_sheet('My Worksheet')
4、往单元格内写入内容
worksheet.write(0, 0, label = 'Row 0, Column 0 Value')
5、保存
workbook.save('Excel_Workbook.xls')
三、写excel表的格式设置
设置单元格宽度:
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write(0, 0,'My Cell Contents')
# 设置单元格宽度
worksheet.col(0).width = 3333
workbook.save('cell_width.xls')
输入一个日期到单元格:
import xlwt
import datetime
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
style = xlwt.XFStyle()
style.num_format_str = 'M/D/YY' # Other options: D-MMM-YY, D-MMM, MMM-YY, h:mm, h:mm:ss, h:mm, h:mm:ss, M/D/YY h:mm, mm:ss, [h]:mm:ss, mm:ss.0
worksheet.write(0, 0, datetime.datetime.now(), style)
workbook.save('Excel_Workbook.xls')
向单元格添加一个公式
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write(0, 0, 5) # Outputs 5
worksheet.write(0, 1, 2) # Outputs 2
worksheet.write(1, 0, xlwt.Formula('A1*B1')) # Should output "10" (A1[5] * A2[2])
worksheet.write(1, 1, xlwt.Formula('SUM(A1,B1)')) # Should output "7" (A1[5] + A2[2])
workbook.save('Excel_Workbook.xls')
向单元格添加一个超链接:
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write(0, 0, xlwt.Formula('HYPERLINK("http://www.google.com";"Google")')) # Outputs the text "Google" linking to http://www.google.com
workbook.save('Excel_Workbook.xls')
合并列和行:
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write_merge(0, 0, 0, 3, 'First Merge') # Merges row 0's columns 0 through 3.
font = xlwt.Font() # Create Font
font.bold = True # Set font to Bold
style = xlwt.XFStyle() # Create Style
style.font = font # Add Bold Font to Style
worksheet.write_merge(1, 2, 0, 3, 'Second Merge', style) # Merges row 1 through 2's columns 0 through 3.
workbook.save('Excel_Workbook.xls')
设置单元格内容的对齐方式:
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
alignment = xlwt.Alignment() # Create Alignment
alignment.horz = xlwt.Alignment.HORZ_CENTER # May be: HORZ_GENERAL, HORZ_LEFT, HORZ_CENTER, HORZ_RIGHT, HORZ_FILLED, HORZ_JUSTIFIED, HORZ_CENTER_ACROSS_SEL, HORZ_DISTRIBUTED
alignment.vert = xlwt.Alignment.VERT_CENTER # May be: VERT_TOP, VERT_CENTER, VERT_BOTTOM, VERT_JUSTIFIED, VERT_DISTRIBUTED
style = xlwt.XFStyle() # Create Style
style.alignment = alignment # Add Alignment to Style
worksheet.write(0, 0, 'Cell Contents', style)
workbook.save('Excel_Workbook.xls')
为单元格议添加边框:
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
borders = xlwt.Borders() # Create Borders
borders.left = xlwt.Borders.DASHED
DASHED虚线
NO_LINE没有
THIN实线
# May be: NO_LINE, THIN, MEDIUM, DASHED, DOTTED, THICK, DOUBLE, HAIR, MEDIUM_DASHED, THIN_DASH_DOTTED, MEDIUM_DASH_DOTTED, THIN_DASH_DOT_DOTTED, MEDIUM_DASH_DOT_DOTTED, SLANTED_MEDIUM_DASH_DOTTED, or 0x00 through 0x0D.
borders.right = xlwt.Borders.DASHED
borders.top = xlwt.Borders.DASHED
borders.bottom = xlwt.Borders.DASHED
borders.left_colour = 0x40
borders.right_colour = 0x40
borders.top_colour = 0x40
borders.bottom_colour = 0x40
style = xlwt.XFStyle() # Create Style
style.borders = borders # Add Borders to Style
worksheet.write(0, 0, 'Cell Contents', style)
workbook.save('Excel_Workbook.xls')
为单元格设置背景色:
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
pattern = xlwt.Pattern() # Create the Pattern
pattern.pattern = xlwt.Pattern.SOLID_PATTERN # May be: NO_PATTERN, SOLID_PATTERN, or 0x00 through 0x12
pattern.pattern_fore_colour = 5 # May be: 8 through 63. 0 = Black, 1 = White, 2 = Red, 3 = Green, 4 = Blue, 5 = Yellow, 6 = Magenta, 7 = Cyan, 16 = Maroon, 17 = Dark Green, 18 = Dark Blue, 19 = Dark Yellow , almost brown), 20 = Dark Magenta, 21 = Teal, 22 = Light Gray, 23 = Dark Gray, the list goes on...
style = xlwt.XFStyle() # Create the Pattern
style.pattern = pattern # Add Pattern to Style
worksheet.write(0, 0, 'Cell Contents', style)
workbook.save('Excel_Workbook.xls')
四、修改已经存在的excel表
1、使用xlutils.copy
首先,将需要更改的excel文件打开,用xlutils包的copy将excel文件对象拷贝一份,然后进行修改操作
具体代码实现:
import xlrd
import xlwt
from xlutils.copy import copy
# 打开想要更改的excel文件
old_excel = xlrd.open_workbook('fileName.xls', formatting_info=True)
# 将操作文件对象拷贝,变成可写的workbook对象
new_excel = copy(old_excel)
# 获得第一个sheet的对象
ws = new_excel.get_sheet(0)
# 新建一个sheet的对象
# ws = new_excel.add_sheet('Sheet1')
# 写入数据
ws.write(0, 0, '第一行,第一列')
ws.write(0, 1, '第一行,第二列')
ws.write(0, 2, '第一行,第三列')
ws.write(1, 0, '第二行,第一列')
ws.write(1, 1, '第二行,第二列')
ws.write(1, 2, '第二行,第三列')
# 另存为excel文件,并将文件命名
new_excel.save('new_fileName.xls')
2、使用openpyxl库
import openpyxl
wb=openpyxl.load_workbook(r'ex.xlsx')
# 获取一个存在的sheet
# ws = wb.get_sheet_by_name('Sheet1') #通过表名获取
# 获取一个存在的sheet
# sheet_names = wb.get_sheet_names()
# ws = wb.get_sheet_by_name(sheet_names[index]) # 通过index的数值获取表
# 新建一个sheet的对象
ws = wb.create_sheet(title='Sheet1',index=0)
#获取行数和列数:
rows = ws.max_row #获取行数
cols = ws.max_column #获取列数
# 写入数据
ws.cell(row = rows + 1,column = cols + 1).value = '添加的内容'
# 写入数据
# 数据表基本信息
# tableValues = [['张学友', 15201062100, 18, '测试数据!'], ['李雷', 15201062598, 19, '测试数据!'],['Marry', 15201062191, 28, '测试数据!']]
# for row in range(len(tableValues)):
# ws.append(tableValues[row])
# 保存文件
wb.save(r'ex.xlsx')
参考文献:
1、http://www.cnblogs.com/MrLJC/p/3715783.html 2018.10.29
2、https://blog.csdn.net/Tulaimes/article/details/71172778 2018.10.29
3、https://www.cnblogs.com/wind-wang/p/5663539.html 2018.10.29
4、https://blog.csdn.net/blog_user_zk/article/details/75334566 2018.10.29
5、https://blog.csdn.net/zh54b5n64vn64654/article/details/81101681 2018.10.29
6、https://www.cnblogs.com/BlueSkyyj/p/7571787.html 2018.10.29