本文實例講述了python通過openpyxl生成Excel文件的方法。分享給大家供大家參考。具體如下:
使用前請先安裝openpyxl:
1
|
easy_install openpyxl |
通過這個模塊可以很方便的導出數據到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
|
from openpyxl.workbook import Workbook from openpyxl.writer.excel import ExcelWriter from openpyxl.cell import get_column_letter from openpyxl.style import Color, Fill from openpyxl.cell import Cell #新建一個workbook wb = Workbook() #第一個sheet是ws ws = wb.worksheets[ 0 ] #設置ws的名稱 ws.title = u "下單統計" #給A1賦值 ws.cell( 'A1' ).value = '%s' % ( "跟隨總數" ) #給A2賦值 #先把數字轉換成字母 col = get_column_letter( 1 ) #賦值 ws.cell( '%s%s' % (col, 2 )).value = '%s' % ("A2“) #字體修改樣式 ##顏色 ws.cell( 'A2' ).style.font.color.index = Color.GREEN ##字體名稱 ws.cell( 'A2' ).style.font.name = 'Arial' ##字號 ws.cell( 'A2' ).style.font.size = 8 ##加粗 ws.cell( 'A2' ).style.font.bold = True ##不知道干啥用的 ws.cell( 'A2' ).style.alignment.wrap_text = True ##背景 好像不太好用 是個BUG ws.cell( 'A2' ).style.fill.fill_type = Fill.FILL_SOLID ws.cell( 'A2' ).style.fill.start_color.index = Color.DARKRED ##修改某一列寬度 ws.column_dimensions[ "C" ].width = 60.0 ##增加一個表 ws = wb.create_sheet() ws.title = u '結單統計' ##保存生成xml file_name = 'test.xlsx' file_dir = '/home/x/' dest_filename = '%s%s' % (file_dir,file_name) ew = ExcelWriter(workbook = wb) ew = ExcelWriter(workbook = wb) |
希望本文所述對大家的Python程序設計有所幫助。