python操作Excal

作者 新城 日期 2017-09-07
python操作Excal
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
#coding='utf-8'
import xlrd
import xlwt
from xlutils.copy import copy

#新建文件并且写入
def write_to_excel_xlwt(x,y,inner,x1,x2,y1,y2):
new_workbook = xlwt.Workbook()
new_sheet = new_workbook.add_sheet("SheetName_test")
new_sheet.write(x, y, inner) #(0,0)坐标 写进去 hello

new_sheet.write_merge(x1,x2,y1,y2, '我是一个合并的单元格')

new_workbook.save(r"Workbook.xls")

#向一个已经存在的文件中写入
def write_to_existed_file(inner,x,y):
rb = xlrd.open_workbook(r"Workbook.xls", formatting_info=True)
wb = copy(rb)
ws = wb.get_sheet(0)
ws.write(x, y, inner)
wb.save(r"Workbook.xls")

write_to_excel_xlwt(0,0,'保存内容',1,2,2,2)
write_to_existed_file('后来进的',5,6)

单元格合并

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#coding='utf-8'

import xlwt

def set_style(name, height, bold=False):
style = xlwt.XFStyle() # 初始化样式

font = xlwt.Font() # 为样式创建字体
font.name = name # 'Times New Roman'
font.bold = bold
font.color_index = 3
font.height = height

borders= xlwt.Borders() #边框
borders.left= 6
borders.right= 6
borders.top= 6
borders.bottom= 6

style.font = font
style.borders = borders
style.color = 'red'
return style

# 写excel
def write_excel():
f = xlwt.Workbook() # 创建工作簿
sheet1 = f.add_sheet('sheet1') # 创建sheet

row0 = ['业务', '状态', '北京', '上海', '广州','深圳','状态小计','合计']
column0 = ['机票', '船票', '火车票','汽车票','其它']
status = ['预订','出票', '退票', '业务小计']
beijing = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]

# 生成第一行
for i in range(0, len(row0)):
#循环写进去 坐标 内容 样式
sheet1.write(0, i, row0[i], set_style('Times New Roman', 220, True))

# 生成第一列和最后一列(合并4行)
i, j = 1, 0
while i < 4 * len(column0) and j < len(column0):
##合并(1,0)(4,0)
##合并(1,7)(4,7)
#循环四次 j控制
sheet1.write_merge(i, i + 3, 0, 0, column0[j], set_style('Arial', 220, True)) # 第一列
sheet1.write_merge(i, i + 3, 7, 7) # 最后一列"合计"
i += 4
j += 1

sheet1.write_merge(21, 21, 0, 1, u'合计', set_style('Times New Roman', 220, True))

# 生成第二列
i = 0
while i < 4 * len(column0):
for j in range(0, len(status)):
sheet1.write(j + i + 1, 1, status[j])
i += 4

#第三列设置数据
b, h =0, 0
#外层循环控制分组
while b < beijing.__len__():
#插入每个分组数据
for j in range(0, beijing[b].__len__()):
sheet1.write(h + 1, 2, beijing[b][j])
# print(beijing[r][j])
print(h + 1,2) #坐标控制
h += 1
b += 1
f.save('demo1.xlsx') # 保存文件

if __name__ == '__main__':
write_excel()