一、代码
import xlwings as xw
import pandas as pd
xl_path=r'***'
df_path=r'***'
df=pd.read_excel(df_path)
app=xw.App(visible=False,add_book=False)
#不弹出提示窗
app.display_alerts=False
load_wb=app.books.open(xl_path)
load_ws=load_wb.sheets["sheetname"]
#清除sheet内的所有数据
load_ws.clear()
#将dataframe转成列表写入
load_ws.range('A1').expand('table').value = df.values.tolist()
load_wb.save()
load_wb.close()
app.quit()
二、改进封装代码
import xlwings as xw
import pandas as pd
import numpy as np
class PathError(BaseException):
def __init__(self, error):
self.error = error
class WriteError(BaseException):
def __init__(self, error):
self.error = error
# 判断元素是否为数字
def is_number(s):
try:
if np.isnan(s) or s == False or s == True:
return False
except Exception:
pass
try:
# 判断是否为浮点数
float(s)
return True
except Exception:
pass
try:
import unicodedata # 处理ASCii码的包
# 把一个表示数字的字符串转换为浮点数返回的函数
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
class ExcelMerge(object):
def __init__(self):
self.app = xw.App(visible=False, add_book=False)
self.app.display_alerts = False
self.load_wb = None
self.load_ws = None
self.data_list = []
def merge(self, master_path=None, retinue_path=None, sheet=0):
if not master_path or not retinue_path:
raise PathError("文件地址不能为空")
self.data_list = self.read_df(master_path)
self.data_list.extend(self.read_df(retinue_path))
self.data_list = pd.DataFrame(self.data_list)
try:
self.load_wb = self.app.books.open(master_path)
self.load_ws = self.load_wb.sheets[sheet]
self.load_ws.range('A2').expand('table').value = self.data_list
except Exception as e:
raise WriteError("excel写入错误:{}".format(e))
finally:
self.load_wb.save()
self.load_wb.close()
self.app.quit()
def read_df(self, path):
df = pd.read_excel(path)
col_list = []
# 以下代码是解决纯数字过长导致写入excel后几位变0
for column in df:
for v in df[column]:
if is_number(v):
if len(str(v)) > 12:
col_list.append(column)
break
if col_list:
for c in col_list:
df[c] = df[c].map(lambda x: "'" + str(x) if not pd.isnull(x) else "")
return df.values.tolist()
em=ExcelMerge()
if __name__ == '__main__':
# 合并2个excel,一个主表,一个从表
master_path="****"
retinue_path="****"
em.merge()