首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何合并多个excel文件并跳过空工作簿

如何合并多个excel文件并跳过空工作簿
EN

Stack Overflow用户
提问于 2022-09-08 05:25:29
回答 2查看 95关注 0票数 0

我必须每天运行数百个数据检查,并将结果合并到一个电子表格中,这样就可以修复错误。我正在尝试编写一些python代码来自动完成这一任务,但我也希望排除任何没有结果的文件。为了使这个问题更加复杂,每个excel文件都有头文件,即使相关的SQL查询没有返回结果。

到目前为止,这就是我所拥有的:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
from pathlib import Path
import time
import xlwings as xw
SOURCE_DIR = [*filepath*]
excel_files = list(Path(SOURCE_DIR).glob('*.csv'))
combined_wb = xw.Book()
t = time.localtime()
timestamp = time.strftime('%Y-%m-%d', t)
for excel_file in excel_files:
    wb = xw.Book(excel_file)
    for sheet in wb.sheets:
            sheet.api.Copy(After=combined_wb.sheets[0].api)
    wb.close()
combined_wb.save([*filepath*]dailychecks_{timestamp}.xlsx")
if len(combined_wb.app.books) == 1:
    combined_wb.app.quit()
else:
    combined_wb.close()

这段代码将给定文件夹中的所有内容合并到一个excel工作簿中,但我不知道如何跳过或忽略这些空文件。如有任何帮助或建议,将不胜感激。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-09-08 07:30:36

下面是将多个.csv文件(通过将它们转换为数据文件)放置在单个Excel文件的不同页中的另一种方法。我们将使用pandas.read_csv创建一个数据文件和一个列表理解,以消除空的数据(没有行的有效标头)。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import pandas as pd #pip install pandas
from pathlib import Path
from time import time

SOURCE_DIR = [*filepath*]
t = time.localtime()
timestamp = time.strftime('%Y-%m-%d', t)

list_of_df = []
for file in Path(SOURCE_DIR).glob('*.csv'):
    temp = pd.read_csv(file)
    list_of_df.append(temp)
            
list_of_df = [df for df in list_of_df if not df.empty] #to get rid of the empty csv/dataframe

with pd.ExcelWriter(f"{SOURCE_DIR}\\dailychecks_{timestamp}.xlsx") as writer:
    for n, df in enumerate(list_of_df):
        df.to_excel(excel_writer= writer, sheet_name= f'Sheet{n+1}', index=False)

如下图所示,这些纸张的名称如下:

您可以通过修改传递给sheet_name of pandas.DataFrame.to_excel的参数的值来改变这一点。

票数 0
EN

Stack Overflow用户

发布于 2022-09-08 07:19:02

这是一种检查工作表是否为空的方法:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
for excel_file in excel_files:
    wb = xw.Book(excel_file)
    for sheet in wb.sheets:
        # if it is not the case that the last cell of the sheet is A1 and A1 is empty
        if not (sheet.range("A1").api.SpecialCells(11).Address == "$A$1") & (sheet.range("A1").value == None):
            sheet.api.Copy(After=combined_wb.sheets[0].api)
    wb.close()
combined_wb.save(f"{SOURCE_DIR}\\dailychecks_{timestamp}.xlsx")

if not语句可以分为两部分:

  1. 使用VBA "SpecialCells",是工作表(编号11) A1上的最后一个单元格吗?如果是,则该单元格是唯一有数据的单元格,或者工作表为空。
  2. 此外,单元格A1的值是否等于None (即为空)?如果也是这样,那么工作表必须是空的。

据我所知,没有一个特定的xlwing函数来检查整个工作表是否为空,因此我不得不使用.api

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73649817

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文