Python excel表格读写,格式化处理

需求:我们公司是做服装零售的,有很多个自营店铺。每个月去店铺盘点,因为设备和网络限制,就用扫描枪直接把盘点货品保存到一个excel表格当中。然后通过excel表格导入到 DRP系统当中。excel表的导入格式是固定的,就货品条码一列。实际我们盘点的时候会分很多列,或者很多品牌等等,这时就需要人工介入处理,相当耗时,通过程序后 人工整理10分钟变一秒。

感受一下

图片一:盘点excel数据源:多列、多品牌、不规则

Python excel表格读写,格式化处理_第1张图片

图片二:目标盘点excel 导入模板

Python excel表格读写,格式化处理_第2张图片

源excel经过工具过渡到目标模板处理:

python + xlrd + xlwt 开发,用了一个 桌面程序显示

Python excel表格读写,格式化处理_第3张图片

输出:每次运行都会单独创建一个文件夹存放

Python excel表格读写,格式化处理_第4张图片

程序核心思路: 1、选中源文件 excel表  2、读取excel所有列 3、写入到新的excel表中 

涉及到基础知识:日期转换字符串、excel表读和写、文件和目录的创建、列表、遍历等等。

图形化编程代码复用。

核心代码块:

1、读入excel,其中针对不同品牌货号做了区分,存储到不同的list中,return一个元祖

	def pd_format_excel(self, file_name):
		if os.path.exists(file_name) == False:
			messagebox.showerror(title='友情提示', message='请选择正确的文件')
		bk = xlrd.open_workbook(file_name)
		sheet1 = bk.sheet_by_index(0)
		# sheet1 = bk.sheet_by_name('Sheet1')
		nrows = sheet1.nrows
		nclos = sheet1.ncols
		klist = []
		mlist = []
		l_list = []
		other_list = []
		for x in range(nrows):
			for y in range(nclos):
				cellvalue = str(sheet1.cell_value(x, y)).upper()

				if cellvalue == '':
					continue
				cellvalue = self.del_style_key(cellvalue)

				if cellvalue.startswith('L'):
					l_list.append(cellvalue)
				elif cellvalue.startswith('K'):
					klist.append(cellvalue)
				elif cellvalue.startswith('M'):
					mlist.append(cellvalue)
				else:
					other_list.append(cellvalue)
		return mlist, l_list, klist, other_list

2、根据返回的 元组数据,一个for循环遍历,写入到excel中

	# 写入excel表格
	def write_pd_excel(self, list):
			# 新建目录:运行目录+当前日期拼接新目录
		dir_name = os.path.join(os.getcwd(), time.strftime("%Y-%m-%d", time.gmtime()) + '盘点明细单')
		if not os.path.exists(dir_name):
			os.makedirs(dir_name)
		file = xlwt.Workbook()  # 创建工作簿
		'''
			创建第一个sheet:
			 sheet1
		'''
		sheet1 = file.add_sheet(u'Sheet1', cell_overwrite_ok=True)
		# 设置列宽
		sheet1.col(0).width = 256 * 30
		# 生成表头第1行标题
		sheet1.write(0, 0, '款号')
		# 从第2行开始遍历excel写入
		i = 1
		# for循环写入盘点明细
		for row in list:
			sheet1.write(i, 0, row)
			# 移动到下一行继续循环
			i += 1
		# 保存文件名拼接: 结算方代码_结算方名称_出入库明细_日期年月.xls
		brandname = self.get_brand_name(list[0][0])
		file_name = brandname + '-' + time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime()) + '盘点明细单' + '.xls'
		# 保存excel,目录+文件名
		file.save(os.path.join(dir_name, file_name))
		self.txt2.insert(END,  file_name + ' 转换完成\n')

功能简单,解决了实际工作中遇到的现实问题,记录下学以致用。

如有需要源码可以e-mail我。

你可能感兴趣的:(python)