excel-python-openpyxl-保存某个xlsx文件中的一个或多个sheet

问题

我有一个xlsx文件,希望保存其中一个sheet,格式、内容、隐藏列什么的,统统保持不变,只提取一张sheet,另存为另一个xlsx文件。

解决方案

一开始我用了pandas,读取然后保存。但是我发现:pandas会忽略格式,如果用pandas读入再写出,被隐藏的列会展示出来,日期也会变成带时分秒的完整形式。

但是如果用openpyxl删除某些sheet再保存的话,会很方便。格式完整,所见即所得。

import openpyxl

def extract_sheet(file_path,out_path):
    wb = openpyxl.load_workbook(file_path)
    use_less = wb.sheetnames
    use_less.remove('这是我要保存的sheet名称')
    for i in use_less:
        wb.remove(wb[i])
    wb.save(out_path)

对于openpyxl和xlwt的讨论

  1. openpyxl不支持写入xls格式
    用pandas写出到excel文件时,如果不指定engine,那默认用的是xlwt。
with pd.ExcelWriter(outfile_name, mode='a', engine="openpyxl") as writer:

如果要写出到xls文件,上面那句会报错

openpyxl.utils.exceptions.InvalidFileException: openpyxl does not support the old .xls file format, please use xlrd to read this file, or convert it to the more recent .xlsx file format.
  1. xlwt不支持追加模式,会报错(如果用上面那条语句,引擎指定为xlwt的话)
ValueError: Append mode is not supported with xlwt!

对于pandas的一点讨论

当然你也可以对某些列作处理,比如对于纯日期列作调整,使用Series.dt.strftime(格式)。举例:
原文件中有一列time,里面的数值都是日期格式。
excel-python-openpyxl-保存某个xlsx文件中的一个或多个sheet_第1张图片

def test_pd():
    sheets = pd.read_excel('XXXXXX.xlsx', sheet_name=None)
    df = sheets['XXXX']
    raw = df['time']
    print(raw[5])
    s1 = df['time'].dt.strftime("%Y-%m-%d")
    print(s1[5])

输出:不作处理,是完整格式,处理后可以自定义。

2020-10-17 00:00:00
2020-10-17

格式描述可以参考这里。感谢这位作者。

如果这一列不是纯日期,里面某些行混合字符串的话,会报错
excel-python-openpyxl-保存某个xlsx文件中的一个或多个sheet_第2张图片
而我这一列的内容大致是:
在这里插入图片描述

你可能感兴趣的:(工作技巧,python,excel)