Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

How to solve the loss of format when modifying data in an excel macro with Python openpyxl (.XLSM)

I am updating an excel Macro with Python openpyxl but when writing it loses the format, The macro has some buttons and when editing it loses them, but if I open it in windows and enable the basic protected view, and then enter the data, it maintains its format and validates the system correctly, this seems very strange to me and I don't know How to enable it with openxl or some library for Linux since I have seen solutions but only in Windows OS,the input data is in a csv file and this is already solved.

import openpyxl
import csv
import argparse

def add_data(dir_document, dir_csv, name_sheet):
total_rows = []
wb = openpyxl.load_workbook(dir_document, keep_vba=True)
print(wb.sheetnames)
sheet = None

for sheet_names in wb.sheetnames:
    list_name_sheet = name_sheet.split(' ')
    list_sheet_names = sheet_names.split(' ')
    equals = 0
    for item in list_sheet_names:
        for item2 in list_name_sheet:
            if item == item2:
                equals += 1
                continue

    if equals > 2:
        sheet = wb[sheet_names]
        print (sheet_names)
        break

with open(dir_csv, newline='', encoding='utf-8') as File:  
    reader = csv.reader(File, delimiter='|',skipinitialspace=True)     
    for row in reader:
        data_row = []
        for data in row:
            
            if data == None or "''" in data:
                value = None
            else:
                try:
                    value = data.encode('ISO-8859-1').decode("utf-8")
                
                except:
                    value = data

            
            data_row.append(value)
          
        total_rows.append(data_row)


i = 0
j = 1
while i < len(total_rows) :
    while j-1 < len(total_rows[i]):
        
        if total_rows[i][j-1] == None:
            sheet.cell(row=11+i, column=j+1).value = ''
            
            j += 1
        else:
            sheet.cell(row=11+i, column=j+1).value = total_rows[i][j-1]
            
            j += 1
    i += 1

wb.save(dir_document) 
question from:https://stackoverflow.com/questions/65643625/how-to-solve-the-loss-of-format-when-modifying-data-in-an-excel-macro-with-pytho

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...