簡體   English   中英

如何使用 Openpyxl Python 將轉換后的文件保存到新的 excel 文件中?

[英]How to save transformed file into new excel file using Openpyxl Python?

我的工作目錄中目前有 3 個 excel 文件。 所有 3 個文件的名稱都以“_Updated.xlsx”結尾。 我想轉換文件,以便刪除每個文件中的所有空行。 我已經為它創建了 function,但唯一的問題是我無法使用以下代碼保存所有轉換后的文件。 不確定哪里出了問題? 創建新文件的原因是我想保存我的原始文件。

Python 代碼

import openpyxl
import os
from openpyxl import load_workbook,Workbook
import glob
from pathlib import Path

Excel_file_path="/Excel"

for file in Path(Excel_file_path).glob('*_Updated.xlsx'):
    wb=load_workbook(file)
    wb_modified = False
    for sheet in wb.worksheets:
        max_row_in_sheet = sheet.max_row
        max_col_in_sheet = sheet.max_column
        
        sheet_modified = False
        if max_row_in_sheet > 1:
            first_nonempty_row = nonempty_row() # Function to find nonempty row
            sheet_modified = del_rows_before(first_nonempty_row) #Function to delete nonempty row
            
            wb_modified = wb_modified or sheet_modified
            if wb_modified:
                for workbook in workbooks:
                    for sheet in wb.worksheets:
                        new_wb = Workbook()
                        ws = new_wb.active
                        for row_data in sheet.iter_rows():
                            for row_cell in row_data:
                                ws[row_cell.coordinate].value = row_cell.value
                                new_wb.save("/Excel/"+sheet.title+"_Transformed.xlsx")

以防萬一,如果有人仍在尋找我上述問題的答案。 以下是對我有用的代碼。

import openpyxl
import os
from openpyxl import load_workbook
import glob
from pathlib import Path

Excel_file_path="/Excel"

for file in Path(Excel_file_path).glob('*_Updated.xlsx'):
    wb=load_workbook(file)
    wb_modified = False
    for sheet in wb.worksheets:
        max_row_in_sheet = sheet.max_row
        max_col_in_sheet = sheet.max_column
        
        sheet_modified = False
        if max_row_in_sheet > 1:
            first_nonempty_row = get_first_nonempty_row() # Function to find nonempty row
            sheet_modified = del_rows_before(first_nonempty_row) #Function to delete nonempty roW
            file_name = os.path.basename(file)
    wb.save("Excel/"+file_name[:-5]+"_Transformed.xlsx")
wb.close()
      

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM