如C1单元格内有3种不同的格式,尝试过xlrd、xlwt、xlutils.copy,发现不可行,最后采用xlwings可以完全保留原格式。
最终保存结果:
xlwings、pandas
import pandas as pd
import xlwings as xw
path = r'E:\python\培训课件\p6-常用文件处理\code\工作簿1.xls'
save_path = r'E:\python\培训课件\p6-常用文件处理\code\工作簿1_out.xls'
app = xw.App(visible=False, add_book=False)
app.display_alerts = False
app.screen_updating = False # 是否实时刷新excel程序的显示内容
wb = app.books.open(path)
ws = wb.sheets[0]
# 按行填充值
# ws[1, 2].value = [1, 2]
# 获取行数
df = pd.read_excel(path, header=0)
row_num = len(df)
para_list = []
for i in range(row_num):
para_list.append(ws[i+1, 4].value)
ws[1, 2].options(transpose=True).value = para_list
# 表格填充,多维数组
# ws[1, 2].options(expand='table').value = [[1, 2], [3, 4]]
# 删除最后几列的内容和格式
rg = ws[0:, 3:]
last_col = rg.clear()
wb.save(save_path)
wb.close()
app.quit()
原文链接:https://blog.csdn.net/cyairhp/article/details/114340049