pywin32处理Excel

文章目录

  • 序言
  • 1 Excel基本操作
  • 2 合并单元格、取消单元格
  • 3 对齐,数据格式设置
  • 4 边框设置,背景填充
  • 5 函数使用(自动求和...)
  • 6 数据转化为图表

序言

Excel官方文档

1 Excel基本操作

获得行列基本信息,设置行列宽度,高度,字体等。

#!/usr/bin/env python3 
# -*- coding:GBK -*-

import  win32com.client
import  os, sys, logging,re
from    logging import  debug, info

#logging.basicConfig( level = logging.DEBUG, format = '[%(filename)s %(lineno)d ] %(message)s')
logging.basicConfig( level = logging.DEBUG, format = ' %(message)s')

def get_full_name(name):
    if ':' in name:
        return name 
    else:
        name = os.path.join(os.getcwd(), name)
    return name

class  Excel(object):
    def  __init__(self, filename ):
        self.filename   = get_full_name(filename)
        self.sheetcount = 0

    def open(self, name=''):
        if(name!=''): self.filename = os.path.join(os.getcwd(), name )
        self.excel =  win32com.client.Dispatch("Excel.Application")
        #可见
        self.excel.Visible = 1 
        #book 
        self.excelbook = self.excel.Workbooks.Open(self.filename, ReadOnly=False)
        info("open  excel: %s",  self.filename )
        self.sheet =  self.excelbook.Worksheets(self.excelbook.Worksheets.Count)
        #self.excel.Workbooks.Add()
        self.sheetcount = 1
        ##
        info( self.sheet.cells( 3,1).Value )  #行,列
        for i  in range(1,10):
            self.sheet.cells( i,3).Value  = "hello world "+str(i)

        #获取一列数据
        self.sheet.Columns(1).Font.Bold = True  #第一列加粗
        self.sheet.Columns(1).Font.Name = "宋体" #字体
        self.sheet.Columns(1).Font.Color = -16776961  #字体颜色
        #设置列宽
        print("列宽: ", self.sheet.Columns(1).ColumnWidth )
        self.sheet.Columns(3).ColumnWidth = 30  #设置列宽
        info("已经使用行数count : %s"%self.sheet.usedrange.rows.count )
        info("已经使用列数count : %s"%self.sheet.usedrange.columns.count )
        #获得一行数据
        #info( self.sheet.Rows(1) )
        self.sheet.Rows(1).RowHeight = 30   #设置行高度


    def new_sheet(self, name=''):
        if (self.sheetcount == 0):  self.open()
        
        #operate first sheet 
        self.sheet = self.excel.Worksheets.Add(None, self.sheet, 1) # (Before、After、Count、Type )
        if ''!= name:  self.sheet.Name =  name 
        return  self.sheet
    
    def save(self):
        info('saving excel: %s'%self.filename)

    def close(self):
        info("close excel: %s "%(self.filename))

if  __name__ == '__main__':
    test = Excel('1.xlsx')
    test.open()
    # test.new_sheet()
    # test.new_sheet()
    test.close()

效果如下:
pywin32处理Excel_第1张图片

2 合并单元格、取消单元格

#!/usr/bin/env python3 
# -*- coding:GBK -*-

import  win32com.client
import  os, sys, logging,re
from    logging import  debug, info

#logging.basicConfig( level = logging.DEBUG, format = '[%(filename)s %(lineno)d ] %(message)s')
logging.basicConfig( level = logging.DEBUG, format = ' %(message)s')


def RGB(r,g,b):
    #奇怪的玩意和普通值反过来的
    return int("%02x%02x%02x"%(b,g,r), 16)

def get_full_name(name):
    if ':' in name:
        return name 
    else:
        name = os.path.join(os.getcwd(), name)
    return name

class  Excel(object):
    def  __init__(self, filename ):
        self.filename   = get_full_name(filename)
        self.sheetcount = 0

    def open(self, name=''):
        if(name!=''): self.filename = os.path.join(os.getcwd(), name )
        self.excel =  win32com.client.Dispatch("Excel.Application")
        #可见
        self.excel.Visible = 1 
        #book 
        self.excelbook = self.excel.Workbooks.Open(self.filename, ReadOnly=False)
        info("open  excel: %s",  self.filename )
        self.sheet =  self.excelbook.Worksheets(self.excelbook.Worksheets.Count)
        #self.excel.Workbooks.Add()
        self.sheetcount = 1
        ##
        info( self.sheet.cells( 3,1).Value )  #行,列
        for i  in range(1,10):
            self.sheet.cells( i,3).Value  = "hello"+str(i)
        # self.sheet.Columns(3).HorizontalAlignment  = -4152  #水平居中:  -4108  靠右边: -4152   靠左:-4131	
        # self.sheet.Columns(3).VerticalAlignment    = -4108  #垂直方向
        # 水平靠右
        self.sheet.Range("A1:C9").HorizontalAlignment = -4152
        # 垂直居中
        self.sheet.Range("A1:C9").VerticalAlignment   = -4108


        #合并单元格  B1,C1个单元格  Merge
        self.sheet.Range("B1:D1").Merge(True) 
        #拆分单元格 UnMerge
        self.sheet.Range("B1").UnMerge()   #数据放在B1
        self.sheet.Range("C1").UnMerge()   #数据放在C1
        #合并列一类类似调整Range范围即可
        
if  __name__ == '__main__':
    test = Excel('1.xlsx')
    test.open()

3 对齐,数据格式设置

水平对齐
垂直对齐

#!/usr/bin/env python3 
# -*- coding:GBK -*-

import  win32com.client
import  os, sys, logging,re
from    logging import  debug, info

#logging.basicConfig( level = logging.DEBUG, format = '[%(filename)s %(lineno)d ] %(message)s')
logging.basicConfig( level = logging.DEBUG, format = ' %(message)s')


def RGB(r,g,b):
    #奇怪的玩意和普通值反过来的
    return int("%02x%02x%02x"%(b,g,r), 16)

def get_full_name(name):
    if ':' in name:
        return name 
    else:
        name = os.path.join(os.getcwd(), name)
    return name

class  Excel(object):
    def  __init__(self, filename ):
        self.filename   = get_full_name(filename)
        self.sheetcount = 0

    def open(self, name=''):
        if(name!=''): self.filename = os.path.join(os.getcwd(), name )
        self.excel =  win32com.client.Dispatch("Excel.Application")
        #可见
        self.excel.Visible = 1 
        #book 
        self.excelbook = self.excel.Workbooks.Open(self.filename, ReadOnly=False)
        info("open  excel: %s",  self.filename )
        self.sheet =  self.excelbook.Worksheets(self.excelbook.Worksheets.Count)
        #self.excel.Workbooks.Add()
        self.sheetcount = 1
        ##
        info( self.sheet.cells( 3,1).Value )  #行,列
        for i  in range(1,10):
            self.sheet.cells( i,3).Value  = "hello"+str(i)
        # self.sheet.Columns(3).HorizontalAlignment  = -4152  #水平居中:  -4108  靠右边: -4152   靠左:-4131	
        # self.sheet.Columns(3).VerticalAlignment    = -4108  #垂直方向
        # 水平靠右
        self.sheet.Range("A1:C9").HorizontalAlignment = -4152
        # 垂直居中
        self.sheet.Range("A1:C9").VerticalAlignment   = -4108

if  __name__ == '__main__':
    test = Excel('1.xlsx')
    test.open()

4 边框设置,背景填充

Range对象

#!/usr/bin/env python3 
# -*- coding:GBK -*-

import  win32com.client
import  os, sys, logging,re
from    logging import  debug, info

#logging.basicConfig( level = logging.DEBUG, format = '[%(filename)s %(lineno)d ] %(message)s')
logging.basicConfig( level = logging.DEBUG, format = ' %(message)s')

def RGB(r,g,b):
    #奇怪的玩意和普通值反过来的
    return int("%02x%02x%02x"%(b,g,r), 16)


def get_full_name(name):
    if ':' in name:
        return name 
    else:
        name = os.path.join(os.getcwd(), name)
    return name

class  Excel(object):
    def  __init__(self, filename ):
        self.filename   = get_full_name(filename)
        self.sheetcount = 0

    def open(self, name=''):
        if(name!=''): self.filename = os.path.join(os.getcwd(), name )
        self.excel =  win32com.client.Dispatch("Excel.Application")
        #可见
        self.excel.Visible = 1 
        #book 
        self.excelbook = self.excel.Workbooks.Open(self.filename, ReadOnly=False)
        info("open  excel: %s",  self.filename )
        self.sheet =  self.excelbook.Worksheets(self.excelbook.Worksheets.Count)
        #self.excel.Workbooks.Add()
        self.sheetcount = 1
        ##
        info( self.sheet.cells( 3,1).Value )  #行,列
        for i  in range(1,10):
            self.sheet.cells( i,3).Value  = "hello world "+str(i)
        self.sheet.Columns(3).AutoFit() #自动调整列宽

        #获取一列数据
        self.sheet.Columns(1).Font.Bold = True  #第一列加粗
        self.sheet.Columns(1).Font.Name = "宋体" #字体
        self.sheet.Columns(1).Font.Color = RGB(0,255,0) #字体颜色  

        #设置边框等信息
        rg = self.sheet.Range( self.sheet.Cells( 1, 1 ), self.sheet.Cells(9,3)  ) #获得一个Range对象
        #rg = self.sheet.Range("A1:C9")   #获得一个Range对象
        rg.BorderAround( 1, 4 )          #边框线样式,线的粗细
        rg.Borders.Color  = RGB(0,0,0)   #边框线颜色
        rg.interior.color = RGB(255,0,0) #填充颜色

    def save(self):
        info('saving excel: %s'%self.filename)

    def close(self):
        info("close excel: %s "%(self.filename))

if  __name__ == '__main__':
    test = Excel('1.xlsx')
    test.open()
    test.close()


pywin32处理Excel_第2张图片

5 函数使用(自动求和…)

只能说官方文档还是强大!!!基本想要的Excel操作基本可以找到。

#!/usr/bin/env python3 
# -*- coding:GBK -*-

import  win32com.client
import  os, sys, logging,re
from    logging import  debug, info

#logging.basicConfig( level = logging.DEBUG, format = '[%(filename)s %(lineno)d ] %(message)s')
logging.basicConfig( level = logging.DEBUG, format = ' %(message)s')

def RGB(r,g,b):
    #奇怪的玩意和普通值反过来的
    return int("%02x%02x%02x"%(b,g,r), 16)

def get_full_name(name):
    if ':' in name:
        return name 
    else:
        name = os.path.join(os.getcwd(), name)
    return name

class  Excel(object):
    def  __init__(self, filename ):
        self.filename   = get_full_name(filename)
        self.sheetcount = 0

    def open(self, name=''):
        if(name!=''): self.filename = os.path.join(os.getcwd(), name )
        self.excel =  win32com.client.Dispatch("Excel.Application")
        #可见
        self.excel.Visible = 1 
        #book 
        self.excelbook = self.excel.Workbooks.Open(self.filename, ReadOnly=False)
        info("open  excel: %s",  self.filename )
        self.sheet =  self.excelbook.Worksheets(self.excelbook.Worksheets.Count)
        #self.excel.Workbooks.Add()
        self.sheetcount = 1
        ##  求第一列的和
        for i  in range(1,10):
            self.sheet.cells( i,1).Value  =  i
        #求和 ActiveSheet.Cells(2, 1).Formula = "=Sum(A1:A9)"
        self.sheet.Cells(10,1).Formula = "=Sum(A1:A9)"
        
if  __name__ == '__main__':
    test = Excel('1.xlsx')
    test.open()

效果:
pywin32处理Excel_第3张图片

6 数据转化为图表

你可能感兴趣的:(工具,python)