Python处理Excel,使用openpyxl库

openpyxl官方文档

openpyxl将工作簿(WorkBook)、工作表(Sheet)、单元格(Cell)作为具体操作Excel的对象。

wb = openpyxl.load_workbook(u'明细表.xlsx')#加载工作簿
wb.save(u"明细表(修改).xlsx")#将修改后的工作簿另存为

二、工作表操作

1、获取当前工作表的名称

使用active或者get_active_sheet()我们可以获取当前操作的工作表。

sheetactive = wb.active
print sheetactive.title
 
sheetactive = wb.get_active_sheet()
print sheetactive.title

2、打开工作表

#打开指定名称的工作表
sheet1 = wb[u"2月2日"] #方法一
sheet2 = wb.get_sheet_by_name(u"2月2日")#方法二
 
#打开指定位置的工作表
sheet_names = wb.get_sheet_names()
sheet1 = wb.get_sheet_by_name(sheet_names[0])

3、创建工作表

创建工作表需要使用create_sheet()函数。

sheet1 = wb.create_sheet() #默认插在最后
sheet1 = wb.create_sheet( index = 0 ) #插在开头
sheet1.title = u"新工作表" #修改表名称
 
sheet1 = wb.create_sheet( title = u"新工作表", index =0 )#名称和位置同时指定
 
#批量生成工作表
i = 0
while(i <= 30):
date = i+1
wb.create_sheet( title = u"3月%s号" % date, index = i )
i =i +1

使用remove_sheet()函数可以删除工作表。

4、删除工作表

remove_sheet()函数的参数不是工作表的名称,而是工作表的对象。例如:

wb.remove_sheet(sheet1)
wb.remove_sheet(wb[u"2月1日"])

三、单元格

sheet1["A4"]= 25 #找到具体的单元格进行数据输入。
 
italic16_Font = Font(size=16, italic=True) #设置字体、大小
sheet['A4'].font = italic24_Font
sheet['A4'] = 'Hello world!'
 
sheet['A10'] = '=SUM(A1:A9)' #输入公式
 
sheet.row_dimensions[1].height = 70
sheet.column_dimensions['B'].width = 20 #设置行高行宽
 
sheet.merge_cells('A1:D3') #合并单元格
sheet.unmerge_cells('A1:D3') #拆分单元格

单元格没有数据时,openpyxl将其表示为none。

注意:

为了防止获取的数据两端有看不见的空格,可以使用strip()

其它处理Excel的Python库

用到再研究吧

xlwings、pandas、win32com、xlsxwriter、DataNitro、xlutils

pandas官方文档

xlwings官方文档