可以使用xlrd,也可以使用openpyxl,但是openpyxl读取不了.xls格式的Excel,需要转成xlsx,有点麻烦,所以使用了xlrd。


读取

  • 打开文件

xlrd也遇到了一点问题,文件如果是xls文件直接打开,在提取合并单元格的时候会拿不到数据,需要加上 formatting_info=True,formatting_info=True的时候打开.xlsx文件会报错NotImplementedError: formatting_info=True not yet implemented,加个if就好了

1
2
3
4
5
workbook = xlrd.open_workbook(path)
if path.split('.xl')[1] == 's':
workbook = xlrd.open_workbook(path, formatting_info=True)
# 获取sheet
sheet = workbook.sheet_by_index(0)
  • 获取所有的合并单元格坐标

突突突

1
2
3
4
5
6
# 获取列数
r_num = sheet.nrows
# 获取行数
c_num = sheet.ncols
merge = sheet.merged_cells
print(merge) # [(1, 5, 0, 1), (1, 5, 1, 2)], 对应上面两个合并的单元格
  • 组装数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
read_data =[]
for r in range(r_num):
li = []
for c in range(c_num):
# 读取每个单元格里的数据,合并单元格只有单元格内的第一行第一列有数据,其余空间都为空
cell_value = sheet.row_values(r)[c]
# 判断空数据是否在合并单元格的坐标中,如果在就把数据填充进去
if cell_value is None or cell_value == '':
for (rlow, rhigh, clow, chigh) in merge:
if rlow <= r < rhigh:
if clow <= c < chigh:
cell_value = sheet.cell_value(rlow, clow)
li.append(cell_value)
read_data.append(li)

写入

使用的是xlwt

  • 直接上代码
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
f = xlwt.Workbook()
sheet1 = f.add_sheet('sheet1', cell_overwrite_ok=True)
headers = ['序号', "姓名", '列表', '1月', '2月', '3月', '4月', '5月']
name = ['1-AAA', '2-BBB', '3-CCC', '4-DDD']
status = ['累计应发数', '累计专项扣除-五险一金', '累计免税收入', '累计扣个税']
# 生成第一行header
for i in range(0,len(headers)):
sheet1.write(0,i,headers[i])

# 生成序号、姓名单元格
i, j = 1, 0
while i < 10*len(name) and j < len(name):
sheet1.write_merge(i,i+9,0,0,name[j].split('-')[0])
sheet1.write_merge(i,i+9,1,1,name[j].split('-')[1])
i += 10
j += 1

#生成列表
i = 0
while i < 10*len(column0):
for j in range(0,len(status)):
sheet1.write(j+i+1,3,status[j])
i += 10
# 保存
f.save(path)

Django导出

  • 服务端代码
1
2
3
4
5
6
7
8
9
10
11
excel_stream = io.BytesIO()
# BytesIO流(在内存中读写)
f.save(excel_stream)
res = excel_stream.getvalue()
excel_stream.close()
response = HttpResponse(content_type='application/vnd.ms-excel')
from urllib import parse
file_name = str(path.name).split('.xls')[0] + '(计算后).xls'
response['Content-Disposition'] = 'attachment;filename=' + parse.quote(file_name)
response.write(res)
return response
  • 前端

写一个简单的form表单就行了