我必须每天运行数百个数据检查,并将结果合并到一个电子表格中,这样就可以修复错误。我正在尝试编写一些python代码来自动完成这一任务,但我也希望排除任何没有结果的文件。为了使这个问题更加复杂,每个excel文件都有头文件,即使相关的SQL查询没有返回结果。
到目前为止,这就是我所拥有的:
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工作簿中,但我不知道如何跳过或忽略这些空文件。如有任何帮助或建议,将不胜感激。
发布于 2022-09-08 07:30:36
下面是将多个.csv文件(通过将它们转换为数据文件)放置在单个Excel文件的不同页中的另一种方法。我们将使用pandas.read_csv创建一个数据文件和一个列表理解,以消除空的数据(没有行的有效标头)。
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的参数的值来改变这一点。
发布于 2022-09-08 07:19:02
这是一种检查工作表是否为空的方法:
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
语句可以分为两部分:
None
(即为空)?如果也是这样,那么工作表必须是空的。据我所知,没有一个特定的xlwing函数来检查整个工作表是否为空,因此我不得不使用.api
。
https://stackoverflow.com/questions/73649817
复制相似问题