Search

Creating a copy of a spreadsheet having only unique rows from a given sheet


Let us say we have the following sheet which has the repeated values highlighted in bold. The following script can be used if we want to create a new sheet having rows with the repeated values of the column ID removed.



The value of file1 points to the original file and copy is the path to the new file to be created.

#!/usr/bin/env python3
"""
Tested on python 3.6
file1 : Path to the original file
copy: Path to the file to be created having unique rows from file1
"""
import pyoo
file1="/media/satish/5229e5b6-0b7b-44ef-a609-5aaf186c6bc4/data/pro_g/python/pyoo/test.ods"
copy="/media/satish/5229e5b6-0b7b-44ef-a609-5aaf186c6bc4/data/pro_g/python/pyoo/copy1.ods"
try:
desktop = pyoo.Desktop('localhost', 2002)
doc1 = desktop.open_spreadsheet(file1)
doc2 = desktop.create_spreadsheet()
except Exception as e :
print(e)
print("\nInvalid path for the files")
quit()
sheet1 = doc1.sheets[0]
sheet2 = doc2.sheets[0]
col=0
try:
column=input('Enter the column header of which unique elements are needed \n')
while (sheet1[0,col].value != column):
col=col+1
except IndexError:
print("Invalid column name")
quit()
i=0
scol=0
while(sheet1[0,scol].value != ''):
sheet2[0,scol].value=sheet1[0,scol].value
sheet2[0,scol].background_color= sheet1[0,scol].background_color
sheet2[0,scol].text_color=sheet1[0,scol].text_color
sheet2[0,scol].font_weight=sheet1[0,scol].font_weight
sheet2[0,scol].border_width=sheet1[0,scol].border_width
sheet2[0,scol].border_color=sheet1[0,scol].border_color
scol=scol+1
while(sheet1[i,col].value != ''):
i=i+1
last=i
x=sheet1[1:last,col].values
unique=list(set(x))
size=len(unique)
j=1
for row in range(last) :
for item in unique :
if(sheet1[row,col].value == item):
print(item)
sheet2[j,:].values = sheet1[row,:].values
j=j+1
unique.remove(item)
break
print("There are " + str(size) +" unique values")
doc2.save(copy)
doc1.close()
doc2.close()


Save the file as create_sheet_unique_rows.py and execute it.



The new file created should look as below.


No comments:

Post a Comment