import xlwings
def main1():
#打开Excel程序并新建一个工作簿
app = xlwings.App(visible=True,add_book=False) #启动Excel程序窗口但是不新建工作簿。visible设置窗口可见性,add_book设置启动Excel程序窗口后是否新建工作簿
workbook = app.books.add() #新建工作簿
def main2():
#创建并保存一个空白的Excel文件
app = xlwings.App(True,False) #打开Excel程序窗口
workBook = app.books.add() #新建工作簿
workBook.save(r'C:\Users\Administrator\Desktop\temp\2.xlsx') #保存到该路径,文件名为2.xlsx
workBook.close() #关闭工作簿
app.quit() #关闭Excel程序
def main3():
#打开存在的Excel文件
app = xlwings.App(visible= True,add_book= False)
workBook = app.books.open(r'C:\Users\Administrator\Desktop\temp\2.xlsx')
def main4():
#给单元格赋值
app = xlwings.App(visible= True,add_book= False)
workBook = app.books.open(r'C:\Users\Administrator\Desktop\temp\2.xlsx')
workSheet = workBook.sheets['sheet1'] #选择工作表名为sheet1的工作表
workSheet.range('A1').value = 'A1' #设置sheet1工作表的A1单元格的值为‘A1’
#input("将关闭")
workBook.close() #不保存、关闭工作簿
app.quit() #关闭Excel程序
def main5():
app = xlwings.App(visible=True,add_book=False)
workBook = app.books.add()
workSheet = workBook.sheets.add("123") #新增一个工作簿“123”
def main6():
#简单实现vlookup函数的效果
#我不大会用vlookup
appTestInstruction = xlwings.App(False,add_book = False)
workBookTestInstruction = appTestInstruction.books.open(r'D:\OneDrive - Platinum\05工作目录\03xxxxx\xxx\009xxx\v1.3\xxxx.xlsx')
workSheetTestInstruction = workBookTestInstruction.sheets['V1.3xxx结果']
appInstructionUsage = xlwings.App(False,add_book = False)
workBookInstructionUsage = appInstructionUsage.books.open(r'D:\OneDrive - Platinum\05工作目录\03xxxxx\xxx\009xxxx\v1.3\xxxxxxx(v1.3).xlsx')
workSheetInstructionUsage = workBookInstructionUsage.sheets['xxxxx统计(4月份)']
index = 1
InstructionUsage_dict = {} #用于存储xxx使用量的字典:{command:使用量}
while True:
#print("进来{}:".format(index),end='')
index += 1
cell_A_Name = 'A{}'.format(index)
if workSheetInstructionUsage.range(cell_A_Name).value != None:
cell_B_Name = 'B{}'.format(index)
InstructionUsage_dict[workSheetInstructionUsage.range(cell_A_Name).value] = workSheetInstructionUsage.range(cell_B_Name).value
#print(workSheetInstructionUsage.range(cell_A_Name).value)
else:
break
print("指令使用量字典的长度:{}".format(len(InstructionUsage_dict)))
#写入对应的值
index = 1
while True:
index += 1
#print("进来{}:\t".format(index),end='')
cell_A_Name = 'A{}'.format(index)
if workSheetTestInstruction.range(cell_A_Name).value != None:
#print(workSheetTestInstruction.range(cell_A_Name).value)
cell_K_Name = 'K{}'.format(index)
for key,value in InstructionUsage_dict.items():
#print(type(key))
if key == workSheetTestInstruction.range(cell_A_Name).value:
print('{} = {}'.format(workSheetTestInstruction.range(cell_A_Name).value,value))
workSheetTestInstruction.range(cell_K_Name).value = value
break
else:
break
workBookTestInstruction.save()
workBookTestInstruction.close()
appTestInstruction.quit()
workBookInstructionUsage.save()
workBookInstructionUsage.close()
appInstructionUsage.quit()
def main7():
#假设上一行中的A列、B列和下一行中的A列、B列值相同,就删除下一行
#假设上一行中的A列、B列和下一行中的A列、B列值不相同,就将下一行的A列和B列的值设为比较基准
#初始基准值为A2、B2值
#本节重点:删除一行
excel = xlwings.App(visible=False,add_book=False)
workBook = excel.books.open(r'D:\OneDrive - Platinum\05工作目录\03xxxx\xxx\016temp\剔除重复服务.xlsx')
workBookSheet_1 = workBook.sheets['Sheet1']
A_value = workBookSheet_1.range('A2').value #初始基准值1
B_value = workBookSheet_1.range('B2').value #初始基准值2
print("基准值:A_value:{}\tB_value:{}".format(A_value,B_value))
index = 2
isAdd = True #是否指导index增加
while True:
if isAdd:
index += 1
A_tempValue = workBookSheet_1.range('A{}'.format(index)).value
B_tempValue = workBookSheet_1.range('B{}'.format(index)).value
if A_tempValue != None and B_tempValue != None:
if A_value == A_tempValue and B_value == B_tempValue:
#删除下一行,禁止index增加
workBookSheet_1.range('A{}'.format(index)).api.EntireRow.Delete()
isAdd = False
else:
#将当前值设置为基准值,指导index增加
A_value = A_tempValue
B_value = B_tempValue
isAdd =True
print("基准值:A_value:{}\tB_value:{}".format(A_value,B_value))
else:
break
workBook.save()
workBook.close()
excel.quit()
def main8():
#若第一个工作表的A列值与第二个工作表的A列值相等,就将第一个工作表的当前行写入到第三个工作表中
#本节重点:复制
excel = xlwings.App(visible=False,add_book=False)
workBook = excel.books.open(r'D:\OneDrive - Platinum\05工作目录\03xxxxx\xxxx\016temp\剔除重复服务.xlsx')
workBookSheet_1 = workBook.sheets['全量去重']
workBookSheet_2 = workBook.sheets['V1.3xx']
workBookSheet_3 = workBook.sheets['V1.3对应的服务']
index_1 = 1 #控制第一个工作表的下标
index_2 = 1 #控制第二个工作表的下标
index_3 = 1 #控制第三个工作表的下标
workBookSheet_2_valueList = [] #存储V1.3的command码
while True:
index_2 += 1
workBookSheet_2_AValue = workBookSheet_2.range('A{}'.format(index_2)).value
if workBookSheet_2_AValue != None:
workBookSheet_2_valueList.append(workBookSheet_2_AValue)
else:
break
while True: #以第一个工作表作为基础遍历
index_1 += 1
workBookSheet_1_AValue = workBookSheet_1.range('A{}'.format(index_1)).value
if workBookSheet_1_AValue != None:
for workBookSheet_2_AValue in workBookSheet_2_valueList:
if workBookSheet_1_AValue == workBookSheet_2_AValue:
#写入到第三个工作表中
workBookSheet_3.range('A{}:c{}'.format(index_3,index_3)).value = workBookSheet_1.range('A{}:c{}'.format(index_1,index_1)).value
index_3 += 1
break
print("workBookSheet_1_AValue:{}".format(workBookSheet_1_AValue))
else:
break
workBook.save()
workBook.close()
excel.quit()
main()
上面的都搜索的到
1、隐藏某列
"C:C").EntireColumn.Hidden = True #隐藏C列
"E:E").EntireColumn.Hidden = True #隐藏E列
如果xlwings找不到操作,请直接搜索使用VBA如何如何,然后通过api调用对应的函数。
关于autofit自动调整,若是之前指定了某个单元格的具体高和宽,随后又使用autofit来自动调整该单元格所在的行或者列的时候,会发现不起作用或者起到反作用,是因为这两种方式以手动指定的高宽为高优先级。
workSheet_shijuan.range("B:B").autofit() #自动调整B列的高,但是之前不能设置B列的高为固定数值
2、判断单元格是否隐藏
if examinationPaper_Sheet.range("A{}".format(index)).height != 0: #隐藏的单元格的高度或者宽度为0,我这里根据我自己的需要只判断高度为0
2021年11月9日更新,有部分可能会重复,大家看的时候ctrl+f搜索一下有没有需要的。
#设置边框线,主要是调用vba去实现的。
resultOutExcel_BookSheet_0.range("A3:AZ{}".format(4+len(EPC_APN_ContentALL))).api.Borders(7).LineStyle = 1 #左线
resultOutExcel_BookSheet_0.range("A3:AZ{}".format(4+len(EPC_APN_ContentALL))).api.Borders(7).Weight = 1
resultOutExcel_BookSheet_0.range("A3:AZ{}".format(4+len(EPC_APN_ContentALL))).api.Borders(8).LineStyle = 1 #顶线
resultOutExcel_BookSheet_0.range("A3:AZ{}".format(4+len(EPC_APN_ContentALL))).api.Borders(8).Weight = 1
resultOutExcel_BookSheet_0.range("A3:AZ{}".format(4+len(EPC_APN_ContentALL))).api.Borders(9).LineStyle = 1 #底线
resultOutExcel_BookSheet_0.range("A3:AZ{}".format(4+len(EPC_APN_ContentALL))).api.Borders(9).Weight = 1
resultOutExcel_BookSheet_0.range("A3:AZ{}".format(4+len(EPC_APN_ContentALL))).api.Borders(10).LineStyle = 1 #右线
resultOutExcel_BookSheet_0.range("A3:AZ{}".format(4+len(EPC_APN_ContentALL))).api.Borders(10).Weight = 1
resultOutExcel_BookSheet_0.range("A3:AZ{}".format(4+len(EPC_APN_ContentALL))).api.Borders(11).LineStyle = 1 #内垂直线
resultOutExcel_BookSheet_0.range("A3:AZ{}".format(4+len(EPC_APN_ContentALL))).api.Borders(11).Weight = 1
resultOutExcel_BookSheet_0.range("A3:AZ{}".format(4+len(EPC_APN_ContentALL))).api.Borders(12).LineStyle = 1 #内水平线
resultOutExcel_BookSheet_0.range("A3:AZ{}".format(4+len(EPC_APN_ContentALL))).api.Borders(12).Weight = 1
#自动调整列宽,resultOutExcel_BookSheet_0:工作表
resultOutExcel_BookSheet_0.autofit(axis="columns") #自动调整列宽
指定列宽
sheet.range("A:Q").column_width=18
指定行高
sheet.range("A:Q").row_height=18
#设置批注
resultOutExcel_BookSheet_0.range('AY4').api.AddComment(Text='筛选时请勿直接点选,而应该输入需要查询的模板ID。')
#内容居中对齐
resultOutExcel_BookSheet_0.range("A3:AZ{}".format(4+len(EPC_APN_ContentALL))).api.HorizontalAlignment = -4108 #-4108 水平居中。 -4131 靠左,-4152 靠右。
resultOutExcel_BookSheet_0.range("A3:AZ{}".format(4+len(EPC_APN_ContentALL))).api.VerticalAlignment = -4108 # -4108 垂直居中(默认)。 -4160 靠上,-4107 靠下, -4130 自动换行对齐。
#内容左对齐
resultOutExcel_BookSheet_0.range("A1:E1").api.HorizontalAlignment = -4131
resultOutExcel_BookSheet_0.range("U4").api.HorizontalAlignment = -4131
#合并单元格
resultOutExcel_BookSheet_0.range("A3:C3").api.Merge() #合并单元格,SHOW EPCAPNNAME
2023年3月24日
连续写一段单元格
#连续写(赋值)一段单元格,批量写数据
result_sheet.range("A{}:E{}".format(i,i)).value = source_sheet.range('A{}:E{}'.format(num,num)).value
c=[[1,2,3],[4,5,6],[7,8,9]]
sheet.range('A1').value=c #从A1开始写如三行三列
2023年7月31日
重命名sheet名称:
sheet.name='新名称'
指定单元格格式
#'@'就表示文本格式,这个可以用录制宏的方式查看
sheet.range("K:K").api.NumberFormatLocal="@"
调整sheet的顺序
#sheet.api.Move(None,After=sheet2.api) #移动到sheet2后面
新建sheet页
sheet=workBook.sheets.add("sheet名")
删除sheet
workBook.sheets[sheet名称].delete()
加粗
sheet.range('B1').api.Font.Bold = True
冻结首行
wb = xlwings.books.active #获取当前激活的sheet
active_window = wb.app.api.ActiveWindow
active_window.SplitColumn = 0 # 冻结至哪一列
active_window.SplitRow = 1 # 冻结至哪一行
active_window.FreezePanes = True #开启冻结
设置单元格规则(条件格式):
#还是那句话,录制宏后改造下
sheet.range("A:B").api.FormatConditions.Add(Type=1, #单元格值
Operator=3, #相等
Formula1="={}".format(变量)) #等于某个预设的变量值
sheet.range("A:B").api.FormatConditions(sheet.range("A:B").api.FormatConditions.Count).SetFirstPriority
sheet.range("A:B").api.FormatConditions(1).Font.Color = -16754788
sheet.range("A:B").api.FormatConditions(1).Font.TintAndShade = 0
sheet.range("A:B").api.FormatConditions(1).Interior.PatternColorIndex = -4105 #xlAutomatic:一个全局常量
sheet.range("A:B").api.FormatConditions(1).Interior.Color = 10284031
sheet.range("A:B").api.FormatConditions(1).Interior.TintAndShade = 0
sheet.range("A:B").api.FormatConditions(1).StopIfTrue = False