1. 程式人生 > >(二)xlwt模組詳解--設定列寬、行高

(二)xlwt模組詳解--設定列寬、行高

第二篇部落格是關於設定Excel中的列寬和行高。

廢話不多說,直接上程式碼看效果!

1.設定列寬

           xlwt中列寬的值表示方法:預設字型0的1/256為衡量單位。其建立時使用的預設寬度為2960,即11個字元0的寬度。所以我們在設定列寬時可以使用如下辦法:

           width = 256 * 20    # 256為衡量單位,20表示20個字元寬度
           那接下來完成我們的程式:

#!/usr/bin/env python3.6
# encoding: utf-8
'''
@author: Leo
@contact: 
@software: PyCharm
@file: excel_width.py
@time: 2018/10/15 下午 05:39
@desc:
'''

import xlwt

workbook = xlwt.Workbook()

worksheet = workbook.add_sheet('My sheet1')

worksheet.write(0, 0, 'My cell Contents')

worksheet.col(0).width = 256 * 20  # Set the column width
worksheet.col(2).width = 8888  # Set the column width

workbook.save('E:\\test\\xls_xlwt\Excel_cell_width.xls')

建立workbook物件、sheet工作表;指定單元格寫入內容;利用索引找出列索引,直接寫寬度。

           效果圖:

怎麼樣?是不是很簡單!

2.設定行高

#!/usr/bin/env python3.6
# encoding: utf-8
'''
    Author: Leo
    Contact: [email protected]
    Software: PyCharm
    File: excel_height.py
    Time: 2018/10/30 上午 08:38
    Desc:
'''

import xlwt

workbook = xlwt.Workbook(encoding='utf-8')  # Create workbook
sheet = workbook.add_sheet('My sheet1')  # Create sheet
first_col = sheet.col(0)
sec_col = sheet.col(1)


first_col.width = 256 * 20  # Set the column width
tall_style = xlwt.easyxf('font:height 720')  # 36pt
first_row = sheet.row(0)
first_row.set_style(tall_style)

workbook.save('E:\\test\\xls_xlwt\Excel_row_height.xls')

效果圖如下:

今日就先更新到這裡~,明天更新內容為合併單元格部分內容。