import xlrd import xlwt import re #首先打开workbook wb = xlrd.open_workbook('统计.xls') #检查表单名字 wb.sheet_names() #得到第一张表单,两种方式:索引和名字 #sh = wb.sheet_by_index() #sh = wb.sheet_by_name() sh = wb.sheets()[0] #读取第一个表单 #输出表格行数 #print(sh.nrows) #输出表格列数 #print(sh.ncols) #输出第一行 #print(sh.row_values(0)) #输出第一列 #print(sh.col_values(0)) #输出元素(0,2)的值 #print(sh.cell(0,2).value) #获取现有行 # homv = sh.nrows dh = sh.col_values(10) dd = [] py = [] # print(sh.col_values(10)) for i in range(sh.nrows): if i == 0 or i == 1: continue if dh[i] not in py: py.append(dh[i]) dd.append(sh.row_values(i)) else: for k,v in enumerate(py): if dh[i] == v: for d in range(int(sh.row_values(i)[5])): dd[k][4] += sh.row_values(i)[4] dd[k][5] = str(int(dd[k][5])+int(sh.row_values(i)[5])) # 创建一个workbook 设置编码 workbook = xlwt.Workbook(encoding = 'utf-8') # 创建一个worksheet worksheet = workbook.add_sheet('My Worksheet') # 写入excel # 参数对应 行, 列, 值 #worksheet.write(1,0, label = 'this is test') # 初始化样式 style = xlwt.XFStyle() # 为样式创建字体 font = xlwt.Font() font.name = 'Times New Roman' font.bold = True # 黑体 #font.underline = True # 下划线 #font.italic = True # 斜体字 #style.font = font # 设定样式 #worksheet.write(1, 0, 'Formatted value', style) # 带样式的写入 #worksheet.write(0, 0, 'Unformatted value') # 不带样式的写入 #worksheet.col(0).width = 3333 # 设置单元格宽度 for k,v in enumerate(dd): y = 5 worksheet.write(k,0,label=v[4]) worksheet.write(k,1,label=v[5]) worksheet.write(k,2,label=v[10]) c = re.compile(r'颜色.(.*?)【加绒加厚】') s = c.findall(v[4]) z = int(v[5]) // 2 for e in range(z): y += 2 if len(s) == 1 and int(v[5]) > 1: for i in range(int(v[5])-1): if v[4].find('88') != -1: y += 21 else: y += 34 for i in s: if i.find('88') != -1: y += 21 else: y += 34 if v[27].find('新疆') != -1: y += 10 worksheet.write(k,3,label=y) #保存文件Excel_test.xls workbook.save('Excel_test.xls')