python使用xlwings合并excel踩坑(格式、copy、进程未退出等问题)

安装使用xlwings、pyinstaller、pip升级

安装xlwings库:
win+R打开运行窗口,cmd,在命令行中输入pip installer xlwings,使用操作看最下面的程序
安装pyinstaller:
命令行中输入pip installer pyinstaller
使用pyinstaller:
pyinstaller -D -w 文件路径\xxx.py
(-F 将py文件打包成一个exe ;-D 打包成一个文件夹 ;-w 运行程序时隐藏命令行窗口,若想看打印信息不写-w即可,默认不写时是-c)
有时出现提醒pip升级:
输入升级即可:python -m pip install --upgrade pip

文件格式混合处理问题(xls、xlsx)

报错信息总览,出现提示:pywintypes.com_error: (-2147352567, ‘发生意外。’, (0, None, None, None, 0, -1880948687), None)
报错信息总览
我在网上找了些pywintypes.com_error: (-2147352567的解决方法,大概是wps进程未关闭、保存的文件格式不正确等等。这些思路无法解决我这个问题,反复测试验证后,发现问题点:

sht_sum = wb_sum.sheets[-1]
wb.sheets[0].copy(after=sht_sum)  #问题在合并这

问题由混合处理xls、xlsx文件引起。将两个文件格式修改为一样即可。我这将xls另存为xlsx文件后处理,问题解决。
注意:直接在文件管理器中修改后缀没有效果,不想用程序处理的话,就用wps或office去另存为一下。

wb_sum = app.books.open(r"{}".format(Filepath2)) #打开xls文件
#另存为xlsx文件  Filepath3 = Filepath2 + "x" 
wb_sum.save(r"{}".format(Filepath3))  #此操作类似于saveas()
wb_sum.close()   #关闭xls文件工作簿
wb_sum = app.books.open(r"{}".format(Filepath3))  #打开新的工作簿,此时文件格式统一

跨工作簿copy报错

报错信息总览,提示pywintypes.com_error: (-2147352567, ‘发生意外。’, (0, None, ‘不支持此接口\r\n’, None, 0, -2147024809), None)。问题点还是在

wb.sheets[0].copy(after=sht_sum)  #又是他哈

在这里插入图片描述
多次尝试后发现与xw.book()和app.books.open()打开方式有关,将打开方式修改即可,解决方法如下:

#wb = xw.Book(r"{}".format(Filepath))
#wb_sum = xw.Book(r"{}".format(Filepath2))
#将上面的打开方式修改为下方的打开方式。
wb = app.books.open(r"{}".format(Filepath))
wb_sum = app.books.open(r"{}".format(Filepath2))

xlwings的两种copy方法

官方文档中的示例如下:

# Create two books and add a value to the first sheet of the first book
first_book = xw.Book()
second_book = xw.Book()
first_book.sheets[0]['A1'].value = 'some value'

# Copy to same Book with the default location and name
first_book.sheets[0].copy()

# Copy to same Book with custom sheet name
first_book.sheets[0].copy(name='copied')

# Copy to second Book requires to use before or after
first_book.sheets[0].copy(after=second_book.sheets[0])

另一种:

sht_sum = wb_sum.sheets[-1]
wb.sheets[0].api.Copy(After=sht_sum.api) #这个也可以

不管用哪一种,上文提到的两个错误一定不能犯,不然报错显示都在这,而这边程序其实都对,咱又不知道真正的原因是什么,容易抓狂。

退出后,wps进程未关闭

当写写程序发现,excel打不开了?只有任务栏里有个任务,桌面上没显示咋办。多半是程序中没将wps进程关闭。手动结束进程即可。
在这里插入图片描述
但是程序总是不关进程也不是个办法,解决方法如下

 wb.save() #保存工作簿
 wb.close() #关闭工作簿
 app.kill() #关闭进程
 #注意:不要用app.quit(),这个退不掉进程。

excel合并小程序(按实际需要自行修改)

from tkinter import *
from tkinter import filedialog
import xlwings as xw
import os

#初始化Tk()
root = Tk()

#设置标题
root.title('Document Merge')

#设置窗口大小
width = 600
height = 300

#自适应屏幕,显示到屏幕正中间
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
alignstr = ("{}x{}+{}+{}".format(width, height, int((screenwidth-width)/2), int((screenheight-height)/2)))
root.geometry(alignstr)

#设置窗口是否可变长、宽,True:可变,False:不可变
root.resizable(width=False, height=False)

text1 = StringVar()
text2 = StringVar()
Filepath = ""
Filepath2 = ""
Filepath3 = ""

def choosefile():
    global Filepath
    Filepath = filedialog.askopenfilename()
    print(Filepath)
    text1.set(Filepath)
    
def choosefile2():
    global Filepath2
    Filepath2 = filedialog.askopenfilename()
    print(Filepath2)
    text2.set(Filepath2)

def choosefile3():
    if(len(Filepath2) == 0):
        return
    global Filepath3
    print(os.path.basename(Filepath2))
    Filepath3 = filedialog.askdirectory(title = "选择保存到文件夹")
    if(len(Filepath3) == 0):
        return
    Filepath3 += '/' + os.path.basename(Filepath2) + 'x';
    print(Filepath3)

def hebing():
    global Filepath3
    choosefile3()
    if (len(Filepath) == 0) or (len(Filepath2) == 0) or (len(Filepath3) == 0 ):
        print("地址空的")
        return
    app = xw.App(visible=False, add_book=False)
    wb = app.books.open(r"{}".format(Filepath))
    wb_sum = app.books.open(r"{}".format(Filepath2))
    wb_sum.save(r"{}".format(Filepath3))
    wb_sum.close()
    wb_sum = app.books.open(r"{}".format(Filepath3))
    if wb_sum.sheets[-1].name == "sheet":
        wb.close()
        wb_sum.close()
        app.kill()
        wb_sum = xw.Book(r"{}".format(Filepath2))
        print("已存在")
        return
    sht = wb.sheets[0]
    sht_row = sht.used_range.last_cell.row
    sht_column = sht.used_range.last_cell.column
    if sht_column > 12 : #根据需求删除文件一中指定列
        sht['Z:AA'].delete()
        sht['W:W'].delete()
        sht['S:T'].delete()
        sht['H:Q'].delete()
    if sht.range('A{}'.format(sht_row-1)).value != "参数一"  and sht.range('A{}'.format(sht_row)).value != "参数一":
        sht.range('A1').value="序号"
        sht.range('a2').options(transpose = True).value = [i for i in range(1,sht_row)]
        sht.range('a{}'.format(sht_row+1)).value = ["参数一","参数二","参数三","参数四"] #num1 num2 num3 num4
        sht.range('a{}'.format(sht_row+2)).value = ["{}".format(num1.get()),"{}".format(num2.get()),"{}".format(num3.get()),"{}".format(num4.get())]

    print(wb_sum.sheets[-1].name)
    sht_sum = wb_sum.sheets[-1]
    wb.sheets[0].copy(after=sht_sum)  #复制到文件二工作表最后
    wb_sum.sheets[-2].delete(); #删除前一个空工作表
    wb_sum.sheets[-1].name = "sheet" #工作表重命名
    
    wb.save()
    wb.close()
    wb_sum.save()
    wb_sum.close()
    app.kill()
    print("合并成功")
    wb_sum = xw.Book(r"{}".format(Filepath3))
    
    Filepath3 = ""
    
#选择文件的按钮    
file_b1 = Button(root, text ="选择文件一", command = choosefile, width = 10 ,height =1).place(x=40 ,y=30)
file_b2 = Button(root, text ="选择文件二", command = choosefile2, width = 10 ,height =1).place(x=40 ,y=80)
#显示地址的label
label1 = Label(root, textvariable =text1, bg='white', width = 60 ,height =1).place(x=140 ,y=35)
label2 = Label(root, textvariable =text2, bg='white', width = 60 ,height =1).place(x=140 ,y=85)

#text显示
Label(root, text ="参数一:", width = 10 ,height =1).place(x=60 ,y=130)
Label(root, text ="参数二:", width = 10 ,height =1).place(x=60 ,y=130+40)
Label(root, text ="参数三:", width = 10 ,height =1).place(x=60 ,y=130+40*2)
Label(root, text ="参数四:", width = 10 ,height =1).place(x=60 ,y=130+40*3)

#文本输入框,注意不要连着写,返回值不对,错例:num1= Entry(root, width = 10 ).place(x=140 ,y=130)
num1= Entry(root, width = 10 )
num1.place(x=140 ,y=130)
num2= Entry(root, width = 10 )
num2.place(x=140 ,y=130 + 40)
num3= Entry(root, width = 10 )
num3.place(x=140 ,y=130 + 40 *2)
num4= Entry(root, width = 10 )
num4.place(x=140 ,y=130 + 40 *3)

#合并文件按钮
merge_b3 = Button(root, text ="合并文件", command = hebing, width = 10 ,height =1).place(x=290 ,y=130)

#进入消息循环
root.mainloop()


运行的gui效果,根据自己的实际需求进行调整吧。
在这里插入图片描述

  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值