win32con操作Excel并且转换为PDF打印

代码

# 先在所需模块 win32con
pip install -i https://pypi.doubanio.com/simple win32con
class FileUp(BaseHandler):

    @tornado.gen.coroutine
    def post(self):
        try:

            files = self.request.files.get('xls', [])
            filename = files[0].get("filename")
            data = files[0].get("body")

            # 创建保存文件夹
            files_path = BASE_DIR
            if not os.path.exists(files_path):
                os.makedirs(files_path)

            # 存储
            xls_path = files_path + "%s" % filename
            with open(xls_path, 'wb') as up:
                up.write(data)

            # 开始填补数据
            # flag = self.fill_xls(xls_path)
            if flag:
                ind = filename.index('.')
                pdf_path = files_path + filename[:ind] + time.strftime("_sj_%Y-%m-%d_%H_%M_%S", time.localtime()) + ".pdf"

                # Open Microsoft Excel
                # pythoncom.CoUninitialize()
                try:
                    xlApp = win32com.client.DispatchEx('Excel.Application')
                    xlApp.Visible = 0  # 不显示
                    xlApp.DisplayAlerts = 0  # 不警告
                    # Read Excel File
                    books = xlApp.Workbooks.Open(xls_path, False)
                    for i in range(0, 8):
                        work_sheets = books.Worksheets[i]  # 获取工作表
                        work_sheets.PageSetup.Orientation = win32con.DMORIENT_LANDSCAPE
                        work_sheets.PageSetup.CenterHorizontally = True
                        work_sheets.PageSetup.Zoom = switcher.get(i)
                        # 页边距
                        work_sheets.PageSetup.LeftMargin = PageMargin[0]
                        work_sheets.PageSetup.RightMargin = PageMargin[1]
                        work_sheets.PageSetup.TopMargin = PageMargin[2]
                        work_sheets.PageSetup.BottomMargin = PageMargin[3]

                        if i in [2,3,4]:
                            work_sheets.PageSetup.PrintArea = '$A$1:$AF$29'
                        if i == 5 :
                            rng_cells = work_sheets.Cells
                            rng_cells.Font.Size = int(FontSize)  # 字号大小
                            work_sheets.UsedRange.RowHeight = int(RowHeight) # 行高
                            work_sheets.PageSetup.PaperSize = 1
                            work_sheets.PageSetup.Zoom = False # 缩放
                            work_sheets.PageSetup.FitToPagesWide = 2 # 分页
                            work_sheets.PageSetup.FitToPagesTall = 10

                    books.ExportAsFixedFormat(0, pdf_path)
                    books.Close(False)
                    xlApp.Quit()
                    # pythoncom.CoUninitialize()



                    filename = filename[:ind] + time.strftime("_sj_%Y-%m-%d_%H_%M_%S", time.localtime()) + ".pdf"
                    self.set_header('Content-Type', 'application/pdf')
                    self.set_header('Content-Disposition', 'attachment; filename=%s' %(filename).encode("UTF-8"))

                    with open(pdf_path, 'rb') as f:
                        while True:
                            data = f.read()
                            if not data:
                                break
                            else:
                                self.write(data)
                    self.finish()

                    # 开始清理文件
                    self.delete_file()
                except Exception as e:
                    logging.error(" * PDF转换失败:", e)
                    books.Close()
                    xlApp.Quit()
                    self.error()
            else:
                logging.error(" * Excel数据填补失败")
                os.remove(xls_path)
                self.error()
        except Exception as e:
            logging.error(" * 请求失败:", e)

win32con本质上是调用本机上的wps或者office程序去完成相关操作的,如果出现程序占用问题,可能会出错;可以在模块加载(DispatchEx)程序前,清理一下后台进程

import psutil

# 清理进程
def killed(self):
    wps = ["wps.exe", "et.exe"]
    s = set(wps)
    for p in psutil.process_iter():
        if p.name() in s:
            p.kill()
            print('killed:' + p.name())
            return
    print('未发现wps相关进程')

相关函数方法

#Excel模块加载 DispatchEx 单独进程启动
xlApp = win32com.client.Dispatch("Excel.Application")
#WPS模块加载
xlApp = win32com.client.Dispatch("et.Application")
#后台运行, 不显示, 不警告
xlApp.Visible = False         # true打开excel程序界面
xlApp.DisplayAlerts =False    # 禁止弹窗-不显示警告信息
# 打开表格
books = xlApp.Workbooks.Open(xls_path, False)

# Sheet页下标从0开始 即为第一个工作表
worksheet = books.Worksheets(0)

# 横向:win32con.DMORIENT_LANDSCAPE 纵向: win32con.DMORIENT_PORTRAIT
worksheet.PageSetup.Orientation = win32con.DMORIENT_LANDSCAPE  # 横向

# 设置缩放比例
worksheet.PageSetup.Zoom = 80

设置N页宽,N页高 #Excel模块加载 DispatchEx 单独进程启动
xlApp = win32com.client.Dispatch("Excel.Application")
#WPS模块加载
xlApp = win32com.client.Dispatch("et.Application")
#后台运行, 不显示, 不警告
xlApp.Visible = False         # true打开excel程序界面
xlApp.DisplayAlerts =False    # 禁止弹窗-不显示警告信息
# 打开表格
books = xlApp.Workbooks.Open(xls_path, False)

# Sheet页下标从0开始 即为第一个工作表
worksheet = books.Worksheets(0)

# 横向:win32con.DMORIENT_LANDSCAPE 纵向: win32con.DMORIENT_PORTRAIT
worksheet.PageSetup.Orientation = win32con.DMORIENT_LANDSCAPE  # 横向

# 设置缩放比例
worksheet.PageSetup.Zoom = 80

# 设置N页宽,N页高 需要先把Zoom关掉,设置成False,才能设置
worksheet.PageSetup.Zoom = False
worksheet.PageSetup.FitToPagesWide = 1
worksheet.PageSetup.FitToPagesTall = 2

# 设置数据居中方式 水平居中方式:CenterHorizontally 垂直居中方式:CenterVertically
worksheet.PageSetup.CenterVertically = True
worksheet.PageSetup.CenterHorizontally = True

# 页边距
worksheet.PageSetup.LeftMargin = 0.5
worksheet.PageSetup.RightMargin = 0.5
worksheet.PageSetup.TopMargin = 0.5
worksheet.PageSetup.BottomMargin = 0.5

# 字体设置
rng_cells = worksheet.Cells
rng_cells.Font.Size = 23                # 字号大小
rng_cells.Font.Name = "黑体"             # 设置字体
worksheet.Cells(1, 1).Interior.Color    # 背景色
worksheet.Range("A1").Formula           # A1单元格写入公式
worksheet.Cells(1,2).Font.Color         # 字体颜色
worksheet.Cells(1,2).Font.Size          # 字体大小
worksheet.Cells(1,2).Font.Bold          # 字体是否为粗体 boolean
worksheet.Cells(1,2).Font.Name          # 字体名称
worksheet.Cells(1,2).Borders.Color      # 网格线
worksheet.Columns.AutoFit()             # 行列自动调整
worksheet.Rows.AutoFit()                # 行列自动调整
worksheet.UsedRange.ColumnWidth = 10    # 设置列宽
worksheet.UsedRange.RowHeight = 15      # 设置行高

基本函数

    import win32com.client as win32
    from win32com.client import Dispatch 
 
    xls = Dispatch('Excel.Application')#打开excel操作环境
    xls = win32com.client.DispatchEx('Excel.Application')
 
    #后台运行, 不显示, 不警告
    xls.Visible = False         # true打开excel程序界面
    xls.DisplayAlerts =False    # 禁止弹窗-不显示警告信息
    # xls.EnableEvents = False  # 禁用事件

workbooks

2.1.说明:
1)工作簿索引从1开始 Workbooks or WorkBooks都可
2)Microsoft对象模型共同特征—对集合依赖。集合看作是列表和字典之间的交叉;
    通过数字索引(括号或方括号)或命名字符串键访问(必须使用括号)
    ws = xlBook.Sheets(1).Name  基于集合索引从1开始 'Sheet1' 
    ws = xlBook.Sheets[1].Name  基于真实位置        'Sheet2' 
3)关键字参数
    Python和Excel都支持关键字参数。调用只需提供所需的参数;关键字大小写必须完全正确。
    Microsoft通常对除Filename之外所有内容都使用大小写混合
 
    WorkBook.SaveAs(Filename, FileFormat, Password, WriteResPassword, ReadOnlyRecommended,
     CreateBackup, AddToMru, TextCodePage, TextVisualLayout)
    调用:xlBook.SaveAs(Filename='C:\\temp\\mysheet.xls') 
 
2.2.访问:
    wb = xlApp.ActiveWorkbook
    wb = xlApp.Workbooks(1)
    wb = xlApp.Workbooks("Book1")    新打开的工作簿(实质上取用工作簿中Name属性的值)
    wb = xlApp.Workbooks('xxx.xlsx') 文件必须已经打开(不能是全路径)
 
2.3.属性:
    wb_n = xls.Workbooks.Count    
    wb_path = xls.Workbooks(i).Path
    wb_name = xls.Workbooks(i).Name
    wb.Checkcompatibility = False
 
2.4.方法:
    xls.Workbooks.Add().Name='book1'      # 创建新的工作簿
    wb = xls.Workbooks.Open('./xxx.xls')  # 打开excel文件
    wb = xls.Workbooks.Open(fullPath, ReadOnly = False)  
    wb = xls.Workbooks.Open(filepath,UpdateLinks=3,ReadOnly=False,Format = None, Password=passWords)
 
    wb.save()                             # 保存当前工作簿
    wb.SaveAs('xxx.xls')                  # 将工作簿另存为
    xls.Workbooks(name_idx).Close(SaveChanges=0) # 关闭当前打开文件,不保存文件
 
    xls.Workbooks(i).Activate()
 
    wb.Quit()
    xls.Application.Quit()
    xls.Quit()                            # 关闭excel操作环境
    del xls
            
    wb.Application.Run(VBA)               #宏
    wb.RunAutoMacros(2)                   #1:打开宏,2:禁用宏

sheets

3.1.说明:
 
3.2.访问:
    ws = xlApp.ActiveSheet  
    ws = xlApp.ActiveWorkbook.ActiveSheet
    ws = xlApp.Workbooks(1).Sheets(1) == wb.Sheets(1)
    ws = xlApp.Workbooks("Book1").Sheets("Sheet1") == wb.Sheets("Sheet1")
 
3.3.属性:
    wb.Worksheets.Count              # 获取工作表个数
    wb.Worksheets(2).Name = 'Details'# 工作簿更名
    sht_names = [ws.Name for ws in xlbook.Worksheets]
    sht_data =[sheetObj.UsedRange.Value for sheetObj in wb.Worksheets]
 
3.4.方法:            
    wb.Worksheets.Add().Name = 'sheet1'           # 新建工作表sheet1
    ws = xls.Sheets(1)=== wb.Worksheets('Sheet1') # 选择工作表-默认Sheet1
    ws.Activate()                                 # 激活当前工作表
    ws.Shapes.AddPicture(picturename, 1, 1, Left, Top, Width, Height)#添加图片
 
    ws = wb.Worksheets(1).Copy(None, sheets(1))   #copy 工作簿 
    shts = self.wb.Worksheets 
    shts(1).Copy(None,shts(1)) 

ranges/cells

4.1.说明:
 
4.2.访问:
    #一个单元格
    wr = ws.Cells(1,1) == xlApp.ActiveSheet.Cells(1,1) 
    wr = ws.Cells(1,1) == xlApp.ActiveWorkbook.ActiveSheet.Cells(1,1) 
    wr = ws.Cells(1,1) == xlApp.Workbooks("Book1").Sheets("Sheet1").Cells(1,1) 
    wr = wb.Sheets(1).Cells(1,1) == xlApp.Workbooks(1).Sheets(1).Cells(1,1).Value 
    wr = wb.Sheets(1).Cells(1,1) == xlApp.Workbooks(1).Sheets(1).Cells(1,1).Value 
 
    #多个单元格           
    wr = ws.Range("B5:C10")      
    wr = ws.Range(ws.Cells(2,2), ws.Cells(3,8))
 
4.3.属性:
    # 获取Excel Data的范围
    n_row = ws.UsedRange.Rows.Count                      # 获取使用区域的行数
    n_col = ws.UsedRange.Columns.Count
    list(ws.Range(ws.Cells(1,2),ws.Cells(row,col)).Value)# 获取所有数据
    
    # 向Excel单元格中写入数据
    wr.Value = 1
    wr.Value = list
    
    ws.Cells(2,1).Value = 3
    ws.Cells(1,1).Value = None                           # Cells(row,col) 
    ws.Cells(11, 5).offset(3,2).Value =1 
    
    ws.Range('D' + str(10)).value = 3.14                 # 第十行
    ws.Range('A1').Value = 'Win32com On Excel'
    
    ws.Range('A2:F2').Value = list('abcDeF')
    ws.Range(ws.Cells(3,1),ws.Cells(3,6)).Value = tuple(range(6))
 
4.4.方法:
    ws.UsedRange.Copy()              # 复制
    ws.UsedRange.Clear()             # 清除内容
    ws.UsedRange.ClearContents()     # 对当前使用区域清除内容
© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容