The boss said that the excel sheet you made was not beautiful and concise? Teach you one trick to get it done with Python

Preface

The text and pictures in this article are from the Internet and are for learning and communication purposes only, and do not have any commercial use. If you have any questions, please contact us for processing.

PS: If you need Python learning materials, you can click on the link below to get it by yourself

Python free learning materials, codes and exchange answers click to join


In this article, I used a Python crawler to crawl the information of popular borrowing books in more than 20 libraries across the country, and compiled statistics according to certain rules, and obtained this list of TOP150 must-read books for college students in various fields. The book list is stored in more than 50 sheet pages in Excel. The file of each sheet page looks like this:

 

Original excel

Original excel

 

Although the content is very valuable, the smell of wine is also afraid of the depth of the alley. No one will be interested in watching these crowded content. At least you have to adjust the format and make a simple beautification to make excel more readable.

If more than 50 shee pages are formatted separately, it is a lot of work. At this time, Python comes in!

I can use Python to beautify these excel formats in batches, saving myself time.

I use the xlwings package for Python's operation of excel.

xlwings can read and write data in Excel files very conveniently, and can modify the cell format. It can also be seamlessly connected with matplotlib, numpy, and pandas. It supports reading and writing numpy and pandas data types, and import matplotlib visualization charts to excel.

More importantly, when operating excel, you can see the effect in real time. It can be said that this is my favorite Python package for handling excel.

The use of xlwings is also very simple, just:

import xlwings as xw

Here we mainly use its function to modify the cell format.
It is divided into three steps:
Step 1 , first make a format template with excel, adjust the row height, column width, etc., and name it sample.xlsx.

Because the row height and column width are both numerical values, it is not intuitive to adjust with code, so the method is adjusted on the template excel and then applied to the target excel. The prepared format template is as follows:

Format template

Format template


The second step is to let the program read the format in this template and tell the program that all the next shee pages will be beautified according to this format.

 


#获取样例表格的列宽数据
def get_sample_format(col):##因为无需读取整个excel所有列的列宽,所以这里传入一个读取的列宽范围参数
    wb = xw.Book("sample.xlsx")  # 建立于sample.xlsx文件的连接
    sheet = wb.sheets["sheet1"] #打开sample.xlsx文件的sheet1
    format = []
    for i in range(col):
        format.append(sheet[0,i].column_width)
    print('列宽:'+str(format))  #'行高:'+sheet.range('A1').column_width+
    wb.close()
    return format

The third step is to let the program operate the 50 shee pages in batches, set according to the column width of the template, and modify some fonts, cell backgrounds, etc. at the same time.


## 美化表格  
def beautiful_sheet(table_name,raw,col,format):
     #设置颜色
    wb2 = xw.Book(table_name)  # 建立excel表连接

    sheets_name= [st.name for st in wb2.sheets]
    for st in  sheets_name:
        sheet2 = wb2.sheets[st]
        # sheet2[0,0] =
        sheet2.range('a1').value= ['序号','书名(@知乎 东写西读整理)','总浏览次数','霸榜高校数','霸榜率','在高校榜单排名中位数','豆瓣评分','豆瓣链接(@知乎 东写西读整理)'] #更改标题行
        sheet2[0:raw,0:col+1].api.Borders(12).LineStyle = 0 #设置单元格横边框为细框线
        sheet2[0:raw, 0:col+1].api.Borders(11).LineStyle = 0 #设置单元格竖边框为细框线
        sheet2[0:raw,0:col].api.Font.Name = '微软雅黑'# 设置字体格式为微软雅黑
        sheet2[0:raw, 0:col].api.HorizontalAlignment = -4108  #设置字体居中
        sheet2[:,4].api.NumberFormat = "0%"    #“霸榜率”这一列单元格设置为百分比格式显示
        for i in range(raw): ##行遍历
                if i==0:
                    sheet2[i, 0:col].color = [217, 217, 217] #设置标题背景颜色格式
                elif i%2 ==0:
                    sheet2[i,0:col].color = [183, 222, 232]    #设置偶数行背景颜色格式为浅蓝色
        for i,item in enumerate(format): #列遍历,根据sample.xlsx中的列宽进行调整
            sheet2[0,i].column_width = item
    wb2.save()#保存excel
    wb2.close()#关闭excel
    return None

Run the program, the optimized excel looks like this:

 

Optimized

Optimized

 

Finally, attach the complete code:

'''
如有需要Python学习资料的小伙伴可以加群领取:1136201545
'''
import xlwings as xw

#获取样例表格的列宽数据
def get_sample_format(col):##因为无需读取整个excel所有列的列宽,所以这里传入一个读取的列宽范围参数
    wb = xw.Book("sample.xlsx")  # 建立于sample.xlsx文件的连接
    sheet = wb.sheets["sheet1"] #打开sample.xlsx文件的sheet1
    format = []
    for i in range(col):
        format.append(sheet[0,i].column_width)
    print('列宽:'+str(format))  #'行高:'+sheet.range('A1').column_width+
    wb.close()
    return format
 ## 美化表格  todo:还需要一个异常退出  https://blog.csdn.net/qq_37289115/article/details/107322332
def beautiful_sheet(table_name,raw,col,format):
     #设置颜色
    wb2 = xw.Book(table_name)  # 建立excel表连接

    sheets_name= [st.name for st in wb2.sheets]
    for st in  sheets_name:
        sheet2 = wb2.sheets[st]
        # sheet2[0,0] =
        sheet2.range('a1').value= ['序号','书名(@知乎 东写西读整理)','总浏览次数','霸榜高校数','霸榜率','在高校榜单排名中位数','豆瓣评分','豆瓣链接(@知乎 东写西读整理)'] #更改标题行
        sheet2[0:raw,0:col+1].api.Borders(12).LineStyle = 0 #设置单元格横边框为细框线
        sheet2[0:raw, 0:col+1].api.Borders(11).LineStyle = 0 #设置单元格竖边框为细框线
        sheet2[0:raw,0:col].api.Font.Name = '微软雅黑'# 设置字体格式为微软雅黑
        sheet2[0:raw, 0:col].api.HorizontalAlignment = -4108  #设置字体居中
        sheet2[:,4].api.NumberFormat = "0%"    #“霸榜率”这一列单元格设置为百分比格式显示
        for i in range(raw): ##行遍历
                if i==0:
                    sheet2[i, 0:col].color = [217, 217, 217] #设置标题背景颜色格式
                elif i%2 ==0:
                    sheet2[i,0:col].color = [183, 222, 232]    #设置偶数行背景颜色格式为浅蓝色
        for i,item in enumerate(format): #列遍历,根据sample.xlsx中的列宽进行调整
            sheet2[0,i].column_width = item
    wb2.save()#保存excel
    wb2.close()#关闭excel
    return None


if __name__ == '__main__':
    table_name = "Top150.xlsx"#需要修改的excel名字
    raw = 151 #需要修改格式的行数
    col = 8  ##需要修改格式的列数
    format = get_sample_format(col)
    beautiful_sheet(table_name,raw,col,format)

Guess you like

Origin blog.csdn.net/pythonxuexi123/article/details/114839961