Skip to main content

        文档函数 - Featured image

文档函数

Openpyxl常用的处理Excel的函数总结

office 2010及以后 .xlsx文件

官网:openpyxl.readthedocs.io

读取文档

import openpyxl as pxl
book = pxl.load_workbook("",data_only =) #book
就是整个Excel文件,data_only = true 会计算所有的公式book得到计算后的值因此无法看到文件原本的公式
sheet = book.worksheets[0]#取第0张工作表 同 sheet =book.active 同 sheet = book["sheet1"] "sheet"是第一个工作表名
    #book.worksheets 代表所有工作表,可以用for循环进行遍历
print(sheet.title)#取出工作表名
print(sheet.min_row,
sheet.max_row)
#取出最小有效行号,最大有效行号
print(sheet.min_column,
sheet.max_column)
#取出最小有效列号,最大有效列号
for row insheet.rows:
                  #按行遍历整个工作表,从第一行到max_row行
for cell in row:
        #遍历一行的单元格,cell是一个单元格
print(cell.value)

     #取出单元格的值,空为None
for cell in sheet["列名"]

          #按列遍历
printcell.value

for cell in sheet[2]

     #按行遍历 
printtype(cell.value), cell.coordinate
,cell.col_idx , cell.number_format#单元格属性:分别是单元格类型(int,str,datetime),单元格坐标,单元格列号,单元格的显示格式(百分比,分数之类)
print(pxl.utils.get_column_letter(1)) #根据列名求取列名
print(pxl.utils.column_index_from_string("A"))#根据列名求取列号

创建文档

import openpyxl as pxl
book =openpyxl.Workbook()#
在内存创建一个Excel文档注意x是大写
sheet = book.active
sheet.title=
"sheet1" #工作表取名为sheet1
data_Rows =
((10,20,30,40.5),(100,200,"=sum(A1:B2)"),[
],["1000",datetime.datetime.now(),"ok"])#只有四种类型,int,float,datetime,str
for row in dataRows:
sheet.append(row)#把数据添加到工作表中
sheet.column_dimensions["B"].width= len(str(sheet["B4"].value))  #设置B列宽度,使其能完整显示B4单元格中的时间,实际上width是字符的个数
sheet["E1"].value = "=sum(A1:D1)" # 赋值,可以设置单元格内容为公式,类型为字符串str
sheet["E2"].number_format =
"0.00" #改变单元格的显示格式
sheet.row_dimensions[2].height= 48 #设置第二行高度为48point
sheet2 = book.create_sheet('sheet2')#添加名为sheet2的工作表,默认新添加的在右边,另外参数可以设置工作表的排序,例如careate_sheet("sheet0",0)
sheet3 =book.copy_worksheet(sheet)#复制工作表sheet并另存为sheet3
book.remove_sheet(book["sheet2"])#删除工作表sheet2
book.save('')保存文件