Modify an existing Excel file using Openpyxl in Python

后端 未结 3 2042
忘掉有多难
忘掉有多难 2020-12-01 04:55

I am basically trying to copy some specific columns from a CSV file and paste those in an existing excel file[*.xlsx] using python. Say for example, you have a CSV file lik

相关标签:
3条回答
  • 2020-12-01 05:15

    In my case, I have kept the excel file open, hence the script could not save and I got permission denied error. After I closed the excel file, my script updated the same excel file.

    0 讨论(0)
  • 2020-12-01 05:29
    from openpyxl import load_workbook
    # Class to manage excel data with openpyxl.
    
    class Copy_excel:
        def __init__(self,src):
            self.wb = load_workbook(src)
            self.ws = self.wb.get_sheet_by_name("Sheet1")
            self.dest="destination.xlsx"
    
        # Write the value in the cell defined by row_dest+column_dest         
        def write_workbook(self,row_dest,column_dest,value):
            c = self.ws.cell(row = row_dest, column = column_dest)
            c.value = value
    
        # Save excel file
        def save_excel(self) :  
            self.wb.save(self.dest)
    
    0 讨论(0)
  • 2020-12-01 05:36

    You can try the following implementation

    from openpyxl import load_workbook
    import csv
    def update_xlsx(src, dest):
        #Open an xlsx for reading
        wb = load_workbook(filename = dest)
        #Get the current Active Sheet
        ws = wb.get_active_sheet()
        #You can also select a particular sheet
        #based on sheet name
        #ws = wb.get_sheet_by_name("Sheet1")
        #Open the csv file
        with open(src) as fin:
            #read the csv
            reader = csv.reader(fin)
            #enumerate the rows, so that you can
            #get the row index for the xlsx
            for index,row in enumerate(reader):
                #Assuming space separated,
                #Split the row to cells (column)
                row = row[0].split()
                #Access the particular cell and assign
                #the value from the csv row
                ws.cell(row=index,column=7).value = row[2]
                ws.cell(row=index,column=8).value = row[3]
        #save the csb file
        wb.save(dest)
    
    • Can we really read a whole column from a CSV file and store into an array/list using python? No, because files are read sequentially, csv reader cannot read a column of data to a row. Instead you may read the whole content and use izip and islice to get a particular column. You can also use numpy.array

    • Can we modify the existing excel file which is in .XLSX format using openpyxl or any other package? Yes, see the example above

    0 讨论(0)
提交回复
热议问题