Skip to content
Advertisement

Can’t write xlsx file to another folder

Please help me, the programmer who made this software is gone and now I’m in trouble: the program opens an xlsx file, inserts some data inside and saves it with another name, I need this file to be saved in a specific directory, can anyone help me? Thank you!

import datetime
import os
from shutil import copyfile
import xml.etree.ElementTree as ET
from openpyxl import load_workbook
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font

class MeasurementsData:
    def __init__(self):
        self.tag = ""
        self.date = ""
        self.filename = ""
        self.application = ""
        self.element = ""
        self.concentration = ""
        self.unit = ""
        self.concentration_results = []

    def parse_empirical_assay(self, result):
        application_methods=result.find('EmpiricalAssayResult').find('ScreeningInfo').findall('ScreeningMethod')
        for method in application_methods:
            if self.application != "":
                self.application += " - "
            self.application += method.attrib['name']

        concentration_results = result.find('EmpiricalAssayResult').find('ConcentrationResults').findall('ConcentrationResult')
        for concentration_result in concentration_results:
            self.concentration_results.append({
                'element': concentration_result.attrib['name'],
                'concentration': concentration_result.attrib['concentration'],
                'unit': concentration_result.attrib['unit']
                })

    def parse_fundamental_parameters(self, result):
        application_methods=result.find('FundamentalParametersResult').find('ScreeningInfo').findall('ScreeningMethod')
        for method in application_methods:
            if self.application != "":
                self.application += " - "
            self.application += method.attrib['name']

        concentration_results = result.find('FundamentalParametersResult').find('ConcentrationResults').findall('ConcentrationResult')
        for concentration_result in concentration_results:
            self.concentration_results.append({
                'element': concentration_result.attrib['name'],
                'concentration': concentration_result.attrib['concentration'],
                'unit': concentration_result.attrib['unit']
                })

    def parse(self, data):
        #print(data)
        xml_data = ET.fromstring(data)
        self.tag = xml_data.attrib['name']
        if self.tag == None or self.tag == "":
            self.tag = "noname"
        self.filename = self.tag + ".xlsx"
        self.date = xml_data.attrib['measurementTime']
        self.date = self.date.split('.')[0]
        self.date=datetime.datetime.strptime(self.date, '%Y-%m-%dT%H:%M:%S')
        #print(self.tag)
        
        result = xml_data.find('Result')
        if result[0].tag == "EmpiricalAssayResult":
            if not os.path.isfile(self.filename):
                copyfile("files/ReportDiMisura1.xlsx", self.filename)
            self.parse_empirical_assay(result)
        elif result[0].tag == "FundamentalParametersResult":
            if not os.path.isfile(self.filename):
                copyfile("files/ReportDiMisura9Colonne2.xlsx", self.filename)
            self.parse_fundamental_parameters(result)
        
        wb = load_workbook(filename = self.filename)
        if wb == None:
            print('File xlsm non trovato!')
            return

        ws = wb['Report']
        if wb == None:
            print('Foglio Report non presente!')
            return

        font = Font(name='Calibri',
            size=11,
            bold=False,
            italic=False,
            vertAlign=None,
            underline='none',
            strike=False,
            color='FF000000')

        alignment = Alignment(horizontal='center',
            vertical='center',
            text_rotation=0,
            wrap_text=False,
            shrink_to_fit=False,
            indent=0)

        cell = ws.cell(row=10, column=2)
        cell.value = self.application
        cell.font = font
        cell.alignment = alignment

        headers_row=23
        row = headers_row+1
        count=1
        cell = ws.cell(row=row, column=1)
        while cell.value != None:
            row += 1
            count += 1
            cell = ws.cell(row=row, column=1)

        if cell.value == None:
            cell.value = self.date #.strftime("%d/%m/%Y %H:%M")
            cell.font = font
            cell.alignment = alignment

            cell = ws.cell(row=row, column=2)
            cell.value = count
            cell.font = font
            cell.alignment = alignment

            column=3
            for concentration_result in self.concentration_results:
                cell = ws.cell(row=headers_row, column=column)
                cell.value = concentration_result['element'] + " " + concentration_result['unit']
                cell.font = font
                cell.alignment = alignment

                cell = ws.cell(row=row, column=column)
                cell.value = float(concentration_result['concentration'])
                cell.font = font
                cell.alignment = alignment
                column+=1

        wb.save (filename  = self.filename)

Advertisement

Answer

In wb.save (filename = self.filename) you can provide any path you need in place of self.filename.

The filename that it gets is defined in the parse method, specifically on following lines:

self.tag = xml_data.attrib['name']
if self.tag == None or self.tag == "":
    self.tag = "noname"
self.filename = self.tag + ".xlsx" 

From there, you can prepend the contents of self.filename with the desired path. Like this for example:

self.filename = "/desired/path/" + self.tag + ".xlsx" # On Linux

or

self.filename = "C:/desired/path/" + self.tag + ".xlsx" # On Windows
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement