python使用xlwings合并excel踩坑(格式、copy、进程未退出等问题)
問題總覽
- 安裝使用xlwings、pyinstaller、pip升級
- 文件格式混合處理問題(xls、xlsx)
- 跨工作簿copy報錯
- xlwings的兩種copy方法
- 退出后,wps進程未關閉
- excel合并小程序(按實際需要自行修改)
安裝使用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進程未關閉、保存的文件格式不正確等等。這些思路無法解決我這個問題,反復測試驗證后,發現問題點:
問題由混合處理xls、xlsx文件引起。將兩個文件格式修改為一樣即可。我這將xls另存為xlsx文件后處理,問題解決。
注意:直接在文件管理器中修改后綴沒有效果,不想用程序處理的話,就用wps或office去另存為一下。
跨工作簿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()打開方式有關,將打開方式修改即可,解決方法如下:
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進程關閉。手動結束進程即可。
但是程序總是不關進程也不是個辦法,解決方法如下
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 FilepathFilepath = filedialog.askopenfilename()print(Filepath)text1.set(Filepath)def choosefile2():global Filepath2Filepath2 = filedialog.askopenfilename()print(Filepath2)text2.set(Filepath2)def choosefile3():if(len(Filepath2) == 0):returnglobal Filepath3print(os.path.basename(Filepath2))Filepath3 = filedialog.askdirectory(title = "選擇保存到文件夾")if(len(Filepath3) == 0):returnFilepath3 += '/' + os.path.basename(Filepath2) + 'x';print(Filepath3)def hebing():global Filepath3choosefile3()if (len(Filepath) == 0) or (len(Filepath2) == 0) or (len(Filepath3) == 0 ):print("地址空的")returnapp = 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("已存在")returnsht = wb.sheets[0]sht_row = sht.used_range.last_cell.rowsht_column = sht.used_range.last_cell.columnif 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 num4sht.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效果,根據自己的實際需求進行調整吧。
總結
以上是生活随笔為你收集整理的python使用xlwings合并excel踩坑(格式、copy、进程未退出等问题)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何用vba在word中快速移动或选中内
- 下一篇: Python迭代器开发