python模塊之XlsxWriter 詳解


Xlsx是python用來構造xlsx文件的模塊,可以向excel2007+中寫text,numbers,formulas 公式以及hyperlinks超鏈接。

可以完成xlsx文件的自動化構造,包括:

合並單元格,制作excel圖表等功能:

1,Introduction:

xlsxWriter支持多種excle功能;與excel完美兼容;寫大文件,速度快且只占用很小的內存空間

不支持讀或者改現有的excel文件

2, Installing:

sudo pip install XlsxWriter;

sudo easy_install XlsxWriter;

或者源碼安裝:http://github.com/jmcnamara/XlsxWriter/archive/master.tar.gz

3,使用:

復制代碼
import xlsxwriter

workbook = xlsxwriter.Workbook('hello.xlsx') # 建立文件

worksheet = workbook.add_worksheet() # 建立sheet, 可以work.add_worksheet('employee')來指定sheet名,但中文名會報UnicodeDecodeErro的錯誤

worksheet.write('A1', 'Hello world') # 向A1寫入

workbook.close()
復制代碼

excel公式計算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Some data we want to write to the worksheet.
expenses  =  (
     [ 'Rent' 1000 ],
     [ 'Gas' ,    100 ],
     [ 'Food' ,   300 ],
     [ 'Gym' ,     50 ],
)
 
# Start from the first cell. Rows and columns are zero indexed. 按標號寫入是從0開始的,按絕對位置'A1'寫入是從1開始的
row  =  0
col  =  0
 
# Iterate over the data and write it out row by row.
for  item, cost  in  (expenses):
     worksheet.write(row, col,     item)
     worksheet.write(row, col  +  1 , cost)
     row  + =  1
 
# Write a total using a formula.
worksheet.write(row,  0 'Total' )
worksheet.write(row,  1 '=SUM(B1:B4)' )     # 調用excel的公式表達式
 
workbook.close()

excel自定義格式:

復制代碼
import xlsxwriter

 # 建文件及sheet.
 workbook = xlsxwriter.Workbook('Expenses02.xlsx')
 worksheet = workbook.add_worksheet()

 # Add a bold format to use to highlight cells. 設置粗體,默認是False
 bold = workbook.add_format({'bold': True})

 # Add a number format for cells with money.  定義數字格式
 money = workbook.add_format({'num_format': '$#,##0'})

 # Write some data headers. 帶自定義粗體blod格式寫表頭
 worksheet.write('A1', 'Item', bold)
 worksheet.write('B1', 'Cost', bold)

 # Some data we want to write to the worksheet.
 expenses = (
     ['Rent', 1000],
     ['Gas',   100],
     ['Food',  300],
     ['Gym',    50],
 )

 # Start from the first cell below the headers.
 row = 1
 col = 0

 # Iterate over the data and write it out row by row.
 for item, cost in (expenses):
     worksheet.write(row, col,     item)    # 帶默認格式寫入
     worksheet.write(row, col + 1, cost, money)  # 帶自定義money格式寫入
     row += 1

 # Write a total using a formula.
 worksheet.write(row, 0, 'Total',       bold)
 worksheet.write(row, 1, '=SUM(B2:B5)', money)

 workbook.close()
復制代碼

 excel寫入時間格式

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from  datetime  import  datetime
  import  xlsxwriter
 
  # Create a workbook and add a worksheet.
  workbook  =  xlsxwriter.Workbook( 'Expenses03.xlsx' )
  worksheet  =  workbook.add_worksheet()
 
  # Add a bold format to use to highlight cells.
  bold  =  workbook.add_format({ 'bold' 1 })
 
  # Add a number format for cells with money.
  money_format  =  workbook.add_format({ 'num_format' '$#,##0' })
 
  # Add an Excel date format.
  date_format  =  workbook.add_format({ 'num_format' 'mmmm d yyyy' })
 
  # Adjust the column width.
  worksheet.set_column( 1 1 15 )
 
  # Write some data headers.
  worksheet.write( 'A1' 'Item' , bold)
  worksheet.write( 'B1' 'Date' , bold)
  worksheet.write( 'C1' 'Cost' , bold)
 
  # Some data we want to write to the worksheet.
  expenses  =  (
      [ 'Rent' '2013-01-13' 1000 ],
      [ 'Gas' ,   '2013-01-14' ,   100 ],
      [ 'Food' '2013-01-16' ,   300 ],
      [ 'Gym' ,   '2013-01-20' ,    50 ],
  )
 
  # Start from the first cell below the headers.
  row  =  1
  col  =  0
 
  for  item, date_str, cost  in  (expenses):
      # Convert the date string into a datetime object.
      date  =  datetime.strptime(date_str,  "%Y-%m-%d" )
 
      worksheet.write_string  (row, col,     item              )
      worksheet.write_datetime(row, col  +  1 , date, date_format )
      worksheet.write_number  (row, col  +  2 , cost, money_format)
      row  + =  1
 
  # Write a total using a formula.
  worksheet.write(row,  0 'Total' , bold)
  worksheet.write(row,  2 '=SUM(C2:C5)' , money_format)
 
  workbook.close()

 @@@ write方法提供了python類型到excel類型的轉換, XlsxWriter支持excel工作表最大1048576行記錄,16384條列記錄,超出可以選擇再建新sheet

1
2
3
4
5
6
7
worksheet.write( 0 0 'Hello' )           # write_string()
worksheet.write( 1 0 'World' )           # write_string()
worksheet.write( 2 0 2 )                 # write_number()
worksheet.write( 3 0 3.00001 )           # write_number()
worksheet.write( 4 0 '=SIN(PI()/4)' )    # write_formula()
worksheet.write( 5 0 , '')                # write_blank()
worksheet.write( 6 0 None )              # write_blank()

 關於更多字符串、數字、顏色及位置等excel格式:http://xlsxwriter.readthedocs.io/format.html

4, 圖標

這個是我比較關注的利用excel工具進行圖標統計的功能

相比較python的matplotlib的畫圖模塊,excel的圖標更加漂亮靈活一些

Chart: Area, Bar, Column, Doughnut, Line, Pie, Scatter, Stock, Radar

workbook = xlswriter.Workbook('chart.xls')

worksheet = workbook.add_sheet('First_example')  # 普通工作表

建立Chart對象: chart = workbook.add_chart({type, 'column'})

 將圖插入到sheet中: worksheet.insert_chart('A7', chart)

或者可以建立圖表工作表chartsheet 

chartsheet = workbook.add_charsheet()

chartsheet.set_char(chart)

柱狀圖:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import  xlsxwriter
 
workbook  =  xlsxwriter.Workbook( 'chart.xlsx' )
worksheet  =  workbook.add_worksheet()
 
# Create a new Chart object.
chart  =  workbook.add_chart({ 'type' 'column' })
 
# Write some data to add to plot on the chart.
data  =  [
     [ 1 2 3 4 5 ],
     [ 2 4 6 8 10 ],
     [ 3 6 9 12 15 ],
]
 
worksheet.write_column( 'A1' , data[ 0 ])   # 按列插入
worksheet.write_column( 'B1' , data[ 1 ])
worksheet.write_column( 'C1' , data[ 2 ])
 
# Configure the chart. In simplest case we add one or more data series.
chart.add_series({ 'values' '=Sheet1!$A$1:$A$5' })
chart.add_series({ 'values' '=Sheet1!$B$1:$B$5' })
chart.add_series({ 'values' '=Sheet1!$C$1:$C$5' })
 
# Insert the chart into the worksheet.
worksheet.insert_chart( 'A7' , chart)
 
workbook.close()

workbook.add_chart({'type':'column'}) # 默認格式

 

workbook.add_chart({'type':'column', 'substyle':'percent_stacked'})  # 按百分比展示

 

workbook.add_chart({'type':'column', 'substyle':'stacked'})

 

其他類型chart也是這樣:




 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com