How to update existing Excel .xlsx file using Openpyxl? - python

I am trying to make this code work, the problem is that in the excel file the print (...) data is not written, I have tried to use ws.appened (...) but without results.
import arcpy
from openpyxl import Workbook
wb = Workbook("C:/Users/Hp/Desktop/ejemplo/VINCULACION_S.xlsx")
ws = wb.active
rows = arcpy.SearchCursor("C:/Users/Hp/Desktop/ejemplo/VH_Dissolve.shp",
fields="COLOR; INTERNO_DE; CLASE_DEMA; COUNT_AREA; SUM_AREA; SUM_LENGTH",
sort_fields="COLOR 222; INTERNO_DE A")
# COLOR, INTERNO_DE, CLASE_DEMA, COUNT_AREA, SUM_AREA y SUM_LENGTH.
for row in rows:
print("Color: {0}, Interno: {1}, Clase:{2}, ContarA: {3}, SumarA: {4}, SumarL: {5}".format(
row.getValue("COLOR"),
row.getValue("INTERNO_DE"),
row.getValue("CLASE_DEMA"),
row.getValue("COUNT_AREA"),
row.getValue("SUM_AREA"),
row.getValue("SUM_LENGTH")))
wb.save('VINCULACION_S.xlsx')
I have also tried to locate the results data in the excel file from cell B3: G3 onwards but I can't find it.

I got this code as a solution to the post
import arcpy
import openpyxl as px
def main():
wb = px.load_workbook(r"C:\Users\Hp\Desktop\Ejemplo\VINCULACION_S.xlsx")
ws = wb['VINCULACION_SH_NUE']
in_features = r"C:\Users\Hp\Desktop\Ejemplo\VH_Dissolve.shp"
row_num = 3
with arcpy.da.SearchCursor(
in_features,
["COLOR", "INTERNO_DE", "CLASE_DEMA", "COUNT_AREA", "SUM_AREA", "SUM_LENGTH"],
) as cursor:
for row in cursor:
ws.cell(row=row_num, column=2).value = row[0]
ws.cell(row=row_num, column=3).value = row[1]
ws.cell(row=row_num, column=4).value = row[2]
ws.cell(row=row_num, column=6).value = row[3]
ws.cell(row=row_num, column=7).value = row[4]
ws.cell(row=row_num, column=8).value = row[5]
row_num += 1
wb.save(r"C:\Users\Hp\Desktop\Ejemplo\VINCULACION_S.xlsx")
if __name__ == "__main__":
main()

Try deleting the content in the existing sheet. Save and reload it.
import arcpy
from openpyxl import Workbook
wb = Workbook("C:/Users/Hp/Desktop/ejemplo/VINCULACION_S.xlsx")
ws = wb.active
k = 100 # approximate no of rows in existing sheet
for i in range(k):
ws.delete_rows(0)
wb.save()
wb = load_workbook("C:/Users/Hp/Desktop/ejemplo/VINCULACION_S.xlsx")
ws = wb.active

Related

Getting wrong value when reading an xlsx file using openpyxl

I'm trying to read values from an xlsx file containing formulas using openpyxl; however, I noticed that for some cells, I'm getting a wrong value.
Here's the XLSX example:
Here's the result I get:
The code:
wb = openpyxl.load_workbook(excel_file, data_only=True)
# getting all sheets
sheets = wb.sheetnames
print(sheets)
# getting a particular sheet
worksheet = wb["Feuil1"]
print(worksheet)
# getting active sheet
active_sheet = wb.active
print(active_sheet)
# reading a cell
print(worksheet["A1"].value)
excel_data = list()
# iterating over the rows and
# getting value from each cell in row
for row in worksheet.iter_rows():
row_data = list()
for cell in row:
#cell.number_format='0.0########'
print(cell.number_format)
row_data.append(str(cell.value))
print(cell.value)
excel_data.append(row_data)
return render(request, 'myapp/index.html', {"excel_data":excel_data})
Hey What you want from an open excel file means which type of format do you gate
data,
This My answer for get data from excel file with xlrd.
import xlrd
from xlrd import open_workbook
fp = tempfile.NamedTemporaryFile(delete= False, suffix=filetype)
fp.write(binascii.a2b_base64(selected file))
workbook = xlrd.open_workbook(file name)
sheet = workbook.sheet_by_name(sheet name)
row = [c or '' for c in sheet.row_values(header_row)]
first_row = []
for col in range(sheet.ncols):
first_row.append(sheet.cell_value(0,col) )
archive_lines = []
for row in range(1, sheet.nrows):
elm = {}
for col in range(sheet.ncols):
elm[first_row[col]]=sheet.cell_value(row,col)
archive_lines.append(elm)

How can I still use functions in excel and print their output ( and not the function) to my python prog.?

This is the code I'm using but, If I use a function in excel, python prints only the function and not it's output. I imagine this is normally fixed using an intermediary like notebook, but the Arabic typeface does not transfer over. Any help you could give would be greatly appreciated.
Thanks,
William M. Hollingsworth
rom openpyxl import load_workbook
def main():
wb = load_workbook(filename ="F:\\Quran Gematria.xlsx", read_only=True)
ws = wb['Sheet1']
bigdict = {}
rowcount = 0
for row in ws.rows:
rowdict = {}
rowdict['words'] = row[0].value
rowdict['sum'] = row[1].value
rowdict['prime']=row[2].value
rowdict['form'] = row[3].value
rowdict['verse'] = row[4].value
bigdict[rowcount] = rowdict
rowcount += 1
for wordkey in bigdict:
if(bigdict[wordkey]['form'] ==74):
print(bigdict[wordkey])
main()
set data_only to True when load workbook:
import openpyxl
wb = openpyxl.load_workbook('forecast.xlsx', data_only=True)

How to write multiple sheets into a new excel, without overwriting each other?

I'm trying to write multiple excels' column A into a new excel's column A (assuming all the excels have one worksheet each.) I've written some code, which can write one excel's column A into the new excel's column A; but if there are multiple excels, the new excel's column A will be overwritten multiple times. So how could I just add all the column As to the new excel sheet one after another without overwriting each other?
Below are my code:
import os, openpyxl
path = os.getcwd()
def func(file):
for file in os.listdir(path):
if file.endswith('.xlsx'):
wb = openpyxl.load_workbook(file)
sheet = wb.active
colA = sheet['A']
wb = openpyxl.Workbook()
r = 1
for i in colA:
sheet = wb.active
sheet.cell(row=r, column=1).value = i.value
r += 1
wb.save('new.xlsx')
func(file)
Thank you so much!!
you could proceed for example as:
import os, openpyxl
path = os.getcwd()
def func(outputFile):
c = 0
#create output workbook
wbOut = openpyxl.Workbook()
sheetOut = wbOut.active
for fName in os.listdir(path):
if fName.endswith('.xlsx'):
c += 1 #move to the next column in output
wb = openpyxl.load_workbook(fName)
sheet = wb.active #input sheet
#for r in range(1, sheet.max_row+1):
# sheetOut.cell(row=r, column=c).value = sheet.cell(row = r, column = 1).value
for r, cell in enumerate(sheet['A']):
sheetOut.cell(row = r+1, column = c).value = cell.value
wbOut.save(outputFile)
#"concatenate" all columns A into one single column
def funcAppend(outputFile):
wbOut = openpyxl.Workbook()
sheetOut = wbOut.active
r = 1
for fName in os.listdir(path):
if fName.endswith('.xlsx'):
wb = openpyxl.load_workbook(fName)
sheet = wb.active
for cell in sheet['A']:
sheetOut.cell(row = r, column = 1).value = cell.value
r += 1
wbOut.save(outputFile)
func('test.xlsx')

write xlsx file using openpyxl module in python

I am having trouble writing to excel file using openpyxl module. So far I am able to write this code
from openpyxl.workbook import Workbook
import datetime
header = [u'Name', u'Email', u'Mobile', u'Current location',]
new_data = [
[u'name1', u'email1#yahoo.com', 9929283421.0, u'xxxx'],
[u'name2', u'email2#xyz.com', 9994191988.0, u'xxxx']
]
wb = Workbook()
cur_date = str(datetime.date.today())
log_file = "%s/%s_%s_errorlog.xlsx" % (settings.MEDIA_ROOT,
os.path.splitext(file_name)[0],
cur_date)
log_csv = wb.worksheets[0]
for i in range(1, len(header) + 1):
log_csv.cell(row = 1 ,column = i).value = header[i - 1]
wb.save(log_file)
error_count = 0
for each_row in new_data:
error_count += 1
for i in range(1, len(each_row) + 1):
log_csv.cell(row = error_count ,column = i).value = each_row[i - 1]
wb.save(log)
File is created, but it is corrupted and I am not able to open it with the excel file reader (LibreOffice) provided by the OS (ubuntu). Also the contents of the file are not readable. Not sure what I am doing wrong
from openpyxl.workbook import Workbook
header = [u'Name', u'Email', u'Mobile', u'Current location',]
new_data = [[u'name1', u'email1#yahoo.com', 9929283421.0, u'xxxx'],
[u'name2', u'email2#xyz.com', 9994191988.0, u'xxxx']]
wb = Workbook()
dest_filename = 'empty_book.xlsx'
ws1 = wb.active
ws1.title = "range names"
ws1.append(header)
for row in new_data:
ws1.append(row)
wb.save(filename = dest_filename)
I am able to write the content to xlsx like above.

Excel File and Sheet Location

I have a list of excel files and their corresponding sheet number. I need python to go to those sheets and find out the cell location for a particular content. Thanks to "alecxe", I used the following code and it worked well.
import xlrd
value = 'Avg.'
fn = ('C:/ab1.xls', 'C:/ab2.xls','C:/ab3.xls','C:/ab4.xls','C:/ab5.xls',)
sn = ('505840', '505608', '430645', '505464', '505084')
for name, sheet_name in zip(fn, sn):
book = xlrd.open_workbook(name)
sheet = book.sheet_by_name(sheet_name)
for row in range(sheet.nrows):
for column in range(sheet.ncols):
if sheet.cell(row,column).value == value:
print row, column
Later I wanted to make changes and instead of writing down the filename and sheetnumber, I wanted python to grab them from an excel sheet. But the program is not printing anything. Can anyone show me where I made the mistake? Highly appreciate your comment!
import xlrd
import glob
import os
value = 'Avg.'
sheetnumber = []
filename = []
xlfile = "C:\\Users\\tsengineer\\Desktop\\Joydip Trial\\Simple.xls"
workbook = xlrd.open_workbook(xlfile)
sheet = workbook.sheet_by_index(0)
for row in range(sheet.nrows):
value = str(sheet.cell_value(row, 17))
filename.append(value)
for row in range(sheet.nrows):
value = str(sheet.cell_value(row, 15))
sheetnumber.append(value)
fn = tuple(filename)
sn = tuple(sheetnumber)
for name, sheet_name in zip(fn, sn):
book = xlrd.open_workbook(name)
sheet = book.sheet_by_name(sheet_name)
for row in range(sheet.nrows):
for column in range(sheet.ncols):
if sheet.cell(row,column).value == value:
print row, column
Definitely for some reasons, the loop is not working as I am getting two empty lists as output. Any thoughts?
import xlrd
value = 'Avg.'
sheetnumber = []
filename = []
rowlist = []
columnlist = []
xlfile = "C:/Users/Joyd/Desktop/Experiment/Simple_1.xls"
workbook = xlrd.open_workbook(xlfile)
sheet = workbook.sheet_by_index(0)
for row in range(sheet.nrows):
value = str(sheet.cell_value(row, 17))
filename.append(value)
for row in range(sheet.nrows):
value = str(sheet.cell_value(row, 15))
sheetnumber.append(value)
fn = tuple(filename)
sn = tuple(sheetnumber)
for fname, sname in zip(fn, sn):
book = xlrd.open_workbook(fname)
sheet = book.sheet_by_name(sname)
for row in range(sheet.nrows):
for column in range(sheet.ncols):
if sheet.cell(row,column).value == value:
rowlist.append(row)
columnlist.append(column)
print rowlist
print columnlist

Categories