pywintypes.com_error: (-2147352567, ‘发生意外。‘, (0, None, None, None, 0, -2147024809), None)

 批量将excel另存为pdf时报错。

  File ">", line 6, in ExportAsFixedFormat
pywintypes.com_error: (-2147352567, '发生意外。', (0, None, None, None, 0, -2147024809), None)

 将报错文件提取出来后运行原路径无误,单独运行报错文件仍然不行。

此时可以将问题定位到文件。

这是一个模糊的报错信息,网上众说纷纭,或说权限问题,或说文件已被打开,或说服务器未正确启动,一一排除后发现是文件存在隐藏表,读取第一个sheet时读取到了隐藏表导致报错。

将隐藏表取消隐藏,或者获取当前活跃表,解决问题。

ws.Visible= False

a=1
while not wb.Worksheets(a).Visible:
    a+=1
ws = wb.Worksheets(a)
import os
import win32process,win32api,win32con
import win32com.client
class abc():
    def __init__(self,path):
        self.path_excels = path
        self.excels = []
        self.name=[]
        self.pdf_small = os.path.join(path, 'pdf')
        if not os.path.exists(self.pdf_small):
            os.makedirs(self.pdf_small)
    def getexcels(self):
        a=0
        for i in os.listdir(self.path_excels):
            if i.split('.')[-1] in ['xlsx', 'xls']:
                a+=1
                this_excel = os.path.join(self.path_excels, i)
                self.excels.append(this_excel)
                target_name = os.path.join(self.pdf_small, str(a) + '.pdf')
                self.name.append(target_name)
    def openexcel(self):
        self.excel = win32com.client.DispatchEx('Excel.Application')
        self.excel.Visible = False  # 是否可视化
        self.excel.DisplayAlerts = False

        for i in range(len(self.excels)):
            self.exceltopdf(i)

        self.close_excel_by_force()

    def exceltopdf(self, i):
        wb = self.excel.Workbooks.Open(self.excels[i], ReadOnly=False)
        ws = wb.Worksheets(1)
        ws.Show(True)
        # target_name=os.path.join(self.pdf_small,self.name[i])
        ws.PageSetup.Zoom = False
        ws.PageSetup.FitToPagesTall = 1
        ws.PageSetup.FitToPagesWide = 1
        print(self.excels[i], self.name[i])
        ws.ExportAsFixedFormat(0, self.name[i][:-4])  # 不需带文件后缀
        wb.Close()

    def run(self):
        try:
            self.getexcels()
            if not self.name: raise TypeError('没有excel文件')
            self.openexcel()
            # shutil.rmtree(self.pdf_small)
        except:
            if self.excel:
                self.close_excel_by_force()
            import traceback
            print(traceback.format_exc())
            # wx.MessageBox(traceback.format_exc())
    def close_excel_by_force(self):  # 关闭进程

        # Get the window's process id's
        hwnd = self.excel.Hwnd
        t, p = win32process.GetWindowThreadProcessId(hwnd)
        # Ask window nicely to close
        try:
            handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p)
            if handle:
                win32api.TerminateProcess(handle, 0)
                win32api.CloseHandle(handle)
        except:
            pass

if __name__=='__main__':
    path = r"C:\Users\gzyz\Desktop\dd\b1"
    abc(path).run()

你可能感兴趣的:(报错分析,win32com,python,开发语言)