溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

使用python庫(kù)xlsxwriter庫(kù)來(lái)輸出各種xlsx文件的示例

發(fā)布時(shí)間:2020-10-10 13:52:05 來(lái)源:腳本之家 閱讀:179 作者:piperck 欄目:開(kāi)發(fā)技術(shù)

功能性的文章直接用幾個(gè)最簡(jiǎn)單的實(shí)現(xiàn)表達(dá):

xlsxwriter庫(kù)的核心就是其Workbook對(duì)象。

創(chuàng)建一個(gè)指定名字的xlsx文件:

import xlsxwriter

filename = '/Users/piperck/Desktop/axiba.xlsx'
test_book = xlsxwriter.Workbook(filename)
worksheet = test_book.add_worksheet()
test_book.close()

創(chuàng)建一個(gè)Workbook的實(shí)例對(duì)象??梢詡魅胍粋€(gè)文件名字,如果不想生成的文件在當(dāng)前路徑下面,可以在文件名字前面帶上絕對(duì)路徑。

add_worksheet()就是增加一個(gè)sheet

然后關(guān)閉這個(gè)對(duì)象,完成xlsx文件的生成。

創(chuàng)建一個(gè)指定名字的sheet并且為其添加一些數(shù)據(jù):

import xlsxwriter

filename = '/Users/piperck/Desktop/axiba.xlsx'
test_book = xlsxwriter.Workbook(filename)
worksheet = test_book.add_worksheet('what')

expenses = (
  ['Rent', 1000],
  ['Gas',  100],
  ['Food', 300],
  ['Gym',  50],
)

# 定義起始的行列 會(huì)在這個(gè)基礎(chǔ)上 行列各加一 作為初始行列
row = 0
col = 0

for item, cost in expenses:
  worksheet.write(row, col, item)
  worksheet.write(row, col+1, cost)
  row += 1

worksheet.write(row, col, '=sum(B0:B4)')
test_book.close()

我們可以使用得到的worksheet對(duì)象來(lái)添加其行列數(shù)據(jù),如上所示。注意最后添加數(shù)據(jù)可以直接在第三個(gè)參數(shù)里面使用函數(shù)。

創(chuàng)建一個(gè)有指定樣式的Workbook:

這個(gè)方法其實(shí)。。應(yīng)該有非常多的參數(shù),大家根據(jù)實(shí)際需要可以具體去查詢(xún)更多的屬性。這個(gè)樣式要在Workbook的對(duì)象上加。

import xlsxwriter

filename = '/Users/piperck/Desktop/axiba.xlsx'
test_book = xlsxwriter.Workbook(filename)
worksheet = test_book.add_worksheet('what')
bold = test_book.add_format({'bold': True})

test_book.add_format()
expenses = (
  ['Rent', 1000],
  ['Gas',  100],
  ['Food', 300],
  ['Gym',  50],
)

# 定義起始的行列 會(huì)在這個(gè)基礎(chǔ)上 行列各加一 作為初始行列
row = 0
col = 0

for item, cost in expenses:
  worksheet.write(row, col, item, bold)
  worksheet.write(row, col+1, cost)
  row += 1

test_book.close()

關(guān)于更多的參數(shù),完全可以參看源代碼里面的property字典下面初始化的那一堆東西,應(yīng)該都是。

根絕著就能解決大部分問(wèn)題了,如果有更多的需求就查閱下面的文檔即可。

通用做法可能會(huì)基于此再做一些東西來(lái)包裝 xlsxwriter 來(lái)讓他更好用,這個(gè)就看大家對(duì)自己業(yè)務(wù)需要抽象的能力了。

Reference:

https://xlsxwriter.readthedocs.io  xlsxwriter doc

在當(dāng)前文件夾生成

#coding=utf-8

def get_excel():
  """
  生成excel
  :return: 
  """
  import xlsxwriter
  workbook = xlsxwriter.Workbook("test.xlsx")
  worksheet = workbook.add_worksheet()
  # 樣式
  formats = Struct() # 字典轉(zhuǎn)化為點(diǎn)語(yǔ)法
  formats.base = {"font_name": u"宋體", "font_size": 11, "align": "center", "valign": "vcenter", "text_wrap": True}
  # formats.condition = dict_merge(formats.base, {"align": "left"})
  formats.bold = {"bold": True} # 加粗
  formats.row = dict_merge(formats.base, {"border": 1})
  formats.first_row = dict_merge(formats.row, {"bold": True}) # 首行
  formats.more_row = dict_merge(formats.row, {}) # 普通行
  formats.more_row_even = dict_merge(formats.row, {"bg_color": "#dddddd"}) # 普通行-奇數(shù)
  # 篩選條件行
  worksheet.merge_range('A1:F1', "") # 合并單元格
  conditions_list = [] # 條件
  province = '省'
  city = '市'
  county = '地區(qū)'
  name = '姓名'
  phone = '電話'
  date = '2018-6'
  if province or city or county:
    area_name = province + city + county
    conditions_list.append(workbook.add_format(formats.bold))
    conditions_list.append(u'地區(qū):')
    conditions_list.append(u'%s ' % area_name)
  if name:
    conditions_list.append(workbook.add_format(formats.bold))
    conditions_list.append(u'姓名:')
    conditions_list.append(u'%s ' % name)
  if phone:
    conditions_list.append(workbook.add_format(formats.bold))
    conditions_list.append(u'手機(jī):')
    conditions_list.append(u'%s ' % phone)
  if date:
    year, month = date[0:4], date[5:7]
    conditions_list.append(workbook.add_format(formats.bold))
    conditions_list.append(u'創(chuàng)建時(shí)間:')
    conditions_list.append(u'%s/%s ' % (year, month))
  if conditions_list: # 如果有條件
    worksheet.write_rich_string('A1', *conditions_list) # 首行

  # 表格首行
  cols = ["姓名", "電話", "地區(qū)"]
  for col_index, col in enumerate(cols):
    worksheet.write(1, col_index, col, workbook.add_format(formats.first_row)) # 第二行,col_index列, col_index從0開(kāi)始,也就是第一列開(kāi)始

  data_list = [{"name": "Spencer", "tel": "13888888888", "reg": "中國(guó)"},{"name": "Jeff", "tel": "139999999999", "reg": "臺(tái)灣省"}]
  # 表格其余行
  for row_index, u in enumerate(data_list, start=2): # 因?yàn)榍皟尚卸急徽加昧?,所以從第三行第一列開(kāi)始
    # 斑馬條
    if row_index % 2 != 0:
      row_format = formats.more_row # excel格式普通行
    else:
      row_format = dict_merge(formats.more_row_even) # excel格式奇數(shù)行
    
    # 日期格式
    date_format = dict_merge(row_format, {"num_format": "yyyy/mm/dd hh:mm"})
    # 靠左
    left_format = dict_merge(row_format, {"align": "left"}) 

    # 第一個(gè)參數(shù):行,第二個(gè)參數(shù):列,第三個(gè)參數(shù):數(shù)據(jù),第四個(gè)參數(shù):屬性
    worksheet.write(row_index, 0, u['name'], workbook.add_format(row_format))
    worksheet.write(row_index, 1, u['tel'], workbook.add_format(row_format))
    worksheet.write(row_index, 2, u['reg'], workbook.add_format(row_format))

    # 列寬 
    # 第一個(gè)參數(shù)是第幾列開(kāi)始,第二個(gè)人參數(shù)是從第幾列結(jié)束
    # 比如下方第一個(gè)就是設(shè)置第一列為20,第二個(gè)就是設(shè)置第二列為10,第三個(gè)就是設(shè)置3到6列為20
  worksheet.set_column(0, 0, 20)
  worksheet.set_column(1, 1, 10)
  worksheet.set_column(2, 5, 20)
  workbook.close()

def dict_merge(*args):
  """
  功能說(shuō)明:合并字典
  """
  all = {}
  for arg in args:
    if not isinstance(arg, dict):
      continue
    all.update(arg)
  return all

class Struct(dict):
  """
  - 為字典加上點(diǎn)語(yǔ)法. 例如:
  >>> o = Struct({'a':1})
  >>> o.a
  >>> 1
  >>> o.b
  >>> None
  """

  def __init__(self, dictobj={}):
    self.update(dictobj)

  def __getattr__(self, name):
    # 如果有則返回值,沒(méi)有則返回None
    if name.startswith('__'):
      raise AttributeError
    return self.get(name)

  def __setattr__(self, name, val):
    self[name] = val

  def __hash__(self):
    return id(self)

if __name__ == '__main__':
  get_excel()

到此這篇關(guān)于使用python庫(kù)xlsxwriter庫(kù)來(lái)輸出各種xlsx文件的示例的文章就介紹到這了,更多相關(guān)python xlsxwriter輸出xlsx內(nèi)容請(qǐng)搜索億速云以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持億速云!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI