Python xlwt工具使用詳解,生成excel欄位寬度可自適應內容長度

xlwt工具使用,生成excel欄位寬度可自適應內容長度

import xlwt
result = [
            ['姓名', '性別', '年齡'],
            ['張三11111111111111111', '男', 186],
            ['李四', '男', 18],
            ['小花', '女', 16],
            ['梅梅', '女', 14],
        ]
 
total = [
            ['男(人)', '女(人)', '共(人)'],
            [2, 2, 4],
        ]
 
# 獲取字符串長度,一個中文的長度為2
def len_byte(value):
    length = len(value)
    utf8_length = len(value.encode('utf-8'))
    length = (utf8_length - length) / 2 + length
    return int(length)
 
#設置字體
font = xlwt.Font()
font.bold = True
 
#設置邊框
borders = xlwt.Borders()
borders.left = xlwt.Borders.THIN
borders.right = xlwt.Borders.THIN
borders.top = xlwt.Borders.THIN
borders.bottom = xlwt.Borders.THIN
 
#設置居中
alignment = xlwt.Alignment()
alignment.horz = xlwt.Alignment.HORZ_CENTER  #水平方向
alignment.vert = xlwt.Alignment.VERT_TOP  #垂直方向
 
#設置背景顏色
pattern = xlwt.Pattern()
pattern.pattern = xlwt.Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = 3  #背景顏色
 
#定義不同的excel style
style1 = xlwt.XFStyle()
style1.font = font
style1.borders = borders
style1.alignment = alignment
style2 = xlwt.XFStyle()
style2.borders = borders
style2.alignment = alignment
style3 = xlwt.XFStyle()
style3.borders = borders
style3.alignment = alignment
style4 = xlwt.XFStyle()
style4.borders = borders
style4.font = font
style4.pattern = pattern
style4.alignment = alignment
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet('My Worksheet')
 
#確定欄位寬度
col_width = []
for i in range(len(result)):
    for j in range(len(result[i])):
        if i == 0:
            col_width.append(len_byte(result[i][j]))
        else:
            if col_width[j] < len_byte(str(result[i][j])):
                col_width[j] = len_byte(result[i][j])
 
#設置欄位寬度,欄位寬度小於10時候采用默認寬度
for i in range(len(col_width)):
    if col_width[i] > 10:
        worksheet.col(i).width = 256 * (col_width[i] + 1)
 
#設置欄位高度
# tall_style = xlwt.easyxf('font:height 720;') #設置字體高度
# row0 = worksheet.row(0)
# row0.set_style(tall_style)
 
#excel內容寫入
for i in range(len(result)):
    for j in range(len(result[i])):
        if i == 0:
            worksheet.write(i, j, label=result[i][j], style=style1)
        else:
            worksheet.write(i, j, label=result[i][j], style=style2)
 
#excel統計結果寫入
for m in range(len(total)):
    for n in range(len(total[m])):
        if m == 0:
            worksheet.write(m + i + 3, n + 2, label=total[m][n], style=style4)
        else:
            worksheet.write(m + i + 3, n + 2, label=total[m][n], style=style2)
 
#合並單元格
worksheet.write_merge(m + i + 4, m + i + 6, 2, 4, label='統計:       簽名:', style=style3)
workbook.save('Excel_Workbook.xls')

xlwt模塊自適應列寬寫入excel

最近需要寫一個用python將數據寫入excel的小工具,遇到瞭自適應列寬寫入excel的問題,特此記錄下解決思路及過程。

運行環境:Windows10、PyCharm 2017.3.2、Python3.6、xlwt1.3.0

編寫小dome如下

import xlwt
'''
利用python的xlwt模塊自適應列寬寫入excel
'''
row_num = 0  # 記錄寫入行數
# 個人信息:姓名,性別,年齡,手機號,固定電話,郵箱
line_name = ['姓名','性別','年齡','手機號','固定電話','郵箱']
data = [
            ['厘清','女','31','18745214693','010-4784125','5412546qq.com'],
            ['張三','男','26','18245554693','010-4784125','無'],
            ['王武','男','19','13245266693','無','785992546qq.com'],
            ['熊大','男','16','無','010-4784125','115412546qq.com'],
            ['熊二','男','22','18745214693','010-4784125','3654126qq.com']
    ]
# 創建一個Workbook對象
book = xlwt.Workbook(encoding="utf-8",style_compression=0)
# 創建一個sheet對象
sheet = book.add_sheet('person_msg', cell_overwrite_ok=True)
# 寫入列名
for name in range(0, len(line_name)):
    sheet.write(row_num, name, line_name[name])
row_num += 1
# 寫入數據
for i in range(0, len(data)):
    for j in range(0, len(data[i])):
        sheet.write(row_num, j, data[i][j])
    row_num += 1
# 保存excel文件
book.save('person_msg.xls')

生成的excel文件沒有任何排版比較亂

解決思路

獲取每列寫入字符長度,比較出每列最寬的長度,最後設置合適的長度。

計算字符串的長度時要註意一個漢字占兩個字節,需要指定字符串的字符集才能獲取正確的字符數

>>> str = 'liming李明'
>>> len(str)
8
>>> len(str.encode('gb18030'))
10

最後代碼如下

import xlwt
import copy
'''
利用python的xlwt模塊自適應列寬寫入excel
'''
# 獲取每列所占用的最大列寬
def get_max_col(max_list):
    line_list = []
    # i表示行,j代表列
    for j in range(len(max_list[0])):
        line_num = []
        for i in range(len(max_list)):
            line_num.append(max_list[i][j])  # 將每列的寬度存入line_num
        line_list.append(max(line_num))  # 將每列最大寬度存入line_list
    return line_list
def write_excel():
    row_num = 0  # 記錄寫入行數
    col_list = []  # 記錄每行寬度
    # 個人信息:姓名,性別,年齡,手機號,固定電話,郵箱
    data = [
                ['姓名','性別','年齡','手機號','固定電話','郵箱'],
                ['厘清','女','31','18745214693','0104784125','5412546qq.com'],
                ['張三','男','26','18245554693','010-4784125','無'],
                ['王武','男','19','13245266693','無','785992546qq.com'],
                ['熊大','男','16','無','010-4784125','115412546qq.com'],
                ['熊二','男','22','18745214693','010-4784125','3654126qq.com']
        ]
    # 創建一個Workbook對象
    book = xlwt.Workbook(encoding="utf-8",style_compression=0)
    # 創建一個sheet對象
    sheet = book.add_sheet('person_msg', cell_overwrite_ok=True)
    col_num = [0 for x in range(0, len(data))]
    # 寫入數據
    for i in range(0, len(data)):
        for j in range(0, len(data[i])):
            sheet.write(row_num, j, data[i][j])
            col_num[j] = len(data[i][j].encode('gb18030')) # 計算每列值的大小
        col_list.append(copy.copy(col_num))  # 記錄一行每列寫入的長度
        row_num += 1
    # 獲取每列最大寬度
    col_max_num = get_max_col(col_list)
    # 設置自適應列寬
    for i in range(0, len(col_max_num)):
        # 256*字符數得到excel列寬,為瞭不顯得特別緊湊添加兩個字符寬度
        sheet.col(i).width = 256 * (col_max_num[i] + 2)
    # 保存excel文件
    book.save('person_msg.xls')
write_excel()

生成excel文件person_msg.xls

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: