在 Python 中为变量添加 .xlsx 扩展名

问题描述 投票:0回答:2

我有一些 Python 代码,可以从 pdf 文件中提取数据并将其转换为 Excel。然后,它从该 Excel 文件中获取特定数据并将其保存到新的 Excel 文件中。我想每次都将最终的 Excel 文件命名为唯一的名称,并认为 datetime.now().isoformat() 将是一个很好的解决方案。因此,我将 datetime.now().isoformat() 保存为字符串,然后希望将 .xlsx 扩展名添加到该字符串以获得唯一名称。但我似乎不知道如何将 .xlsx 附加到变量。

from spire.pdf.common import \*
from spire.pdf import \*
import os
import openpyxl
from openpyxl import load_workbook
from datetime import datetime
import xlsxwriter

current_dateTime = datetime.now().isoformat()
**#This is where I create the variable with the .xlsx extension**
dt = str(current_dateTime) + ".xlsx"

pdf = PdfDocument()
pdf.LoadFromFile("c:/Documents/Projects/file.pdf")

pdf.SaveToFile("excel/template.xlsx", FileFormat.XLSX)
pdf.Close()

folder = 'excel'
**#This is where I try to create the output file with the .xlsx extension**
output_file = dt

output_wb = openpyxl.Workbook()
output_sheet = output_wb.active
output_sheet.title = 'Bearskin'

cells = \['BQ34', 'G13', 'J22'\]

for filename in os.listdir(folder):
    if filename.endswith('.xlsx'):
    file = os.path.join(folder, filename)
    workbook = openpyxl.load_workbook(file)
    values = \[workbook.active\[cell\].value for cell in cells\]
output_sheet.append(values)

output_sheet.insert_rows(1)

output_sheet\['A1'\]= "Section"
output_sheet\['B1'\]= "Operation"
output_sheet\['C1'\]= "Depth"
output_sheet\['D1'\]= "Duration"
output_sheet\['E1'\]= "Cumulative Hours"
output_sheet\['F1'\]= "Cumulative Days"

output_wb.save(output_file)
python
2个回答
0
投票

您可以通过多种方式连接字符串,其中之一是:

output_file = str(dt) + ".xlsx"

对于更高级的用法,您可以使用内置的

format
%
函数,其工作方式类似于 C
printf
函数。

示例:

output_file = "{}.xlsx".format(dt))

0
投票

问题在于提取日期时间并尝试将其用作 dt 的变量。当我使用 (''.join(random.choices(string.ascii_lowercase, k=12))) 创建随机字符串时,它可以工作。因此,对于尝试执行此操作的任何人:创建一个随机字符串,而不是尝试使用日期时间作为变量。

© www.soinside.com 2019 - 2024. All rights reserved.