For some reason Openpyxl won't save the the xlsx file at the end of the program.
I am trying to read measurments from a file, each line is a different measurement. I want to take them and write them to excel as to make using this data later on easier. Everything seems to work, but in the end the data isn't saved, if i create new file where the changes should be saved it will not be created.
from openpyxl import load_workbook
from openpyxl import Workbook
wb = load_workbook(filename='Data_Base.xlsx')
sheet = wb.worksheets[0]
BS = []
Signal = []
with open('WifiData2.txt') as f:
for line in f:
y = int(line.split('|')[0].split(';')[3])
x = int(line.split('|')[0].split(';')[2])
floor = int(x = line.split('|')[0].split(';')[1])
data = line.split("|")[1].strip()
measurements = data.split(";")
for l in measurements:
raw = l.split(" ")
BSSID = raw[0]
signal_strength = raw[1]
print(signal_strength)
BS.append(BSSID)
Signal.append(signal_strength)
for row_num in range(sheet.max_row):
num = row_num
if row_num > 1:
test_X = int(sheet.cell(row=row_num, column=4).value)
test_Y = int(sheet.cell(row=row_num, column=3).value)
test_floor = int(sheet.cell(row=row_num, column=2).value)
if (test_X == x and test_Y == y and test_floor == floor):
nr = nr + 1
if (nr > 3):
q = 1
if (q == 0):
sheet.cell(row=sheet.max_row+1, column = 2, value = floor)
sheet.cell(row=sheet.max_row + 1, column=3, value=x)
sheet.cell(row=sheet.max_row + 1, column=4, value=y)
sheet.cell(row=sheet.max_row + 1, column=2, value=sheet.max_row)
for element in BS:
nr = 0
for col in sheet.max_column:
if BS[element] == sheet.cell(row=1, column=col).value:
sheet.cell(row=sheet.max_row + 1, column=col, value=Signal[element])
nr = 1
if (nr == 0):
sheet.cell(row=1, column=sheet.max_column+1, value=BS[element])
sheet.cell(row=sheet.max_row+1, column=sheet.max_column + 1, value=BS[element])
Signal.clear()
BS.clear()
wb.save('Data_Base1.xlsx')
What is weird that if i save the workbook earlier it will create the file. Of course it doesnt really work for me since any changes that i want made won't be made. I had similar issue when i tried it with xlrd/wt/utils combo. Does any1 know where the problem is ?
Use absolute path instead of relative path will do the trick!
Add
wb.template = False
before
wb.save('Filename.xlsx')
Related
i have a problem with my script.
I`ve made a script that fetch some datas from lines of a raw.txt file into columns to excel.
Its worked at the beggining but now when i added more datas in the file its not, if you can help me or have another solve.
**This is my script:
import xlrd, xlwt, re
from svnscripts.timestampdirectory import createdir, path_dir
import os
import pandas as pd
import time
def clearcasevobs():
pathdest = path_dir()
dest = createdir()
timestr = time.strftime("%Y-%m-%d")
txtName = rf"{pathdest}\{timestr}-clearcaseRawData-vobsDetails.txt"
workBook = xlwt.Workbook(encoding='ascii')
workSheet = workBook.add_sheet('sheet1')
fp = open(txtName, 'r+b')
# header
workSheet.write(0, 0, "Tag")
workSheet.write(0, 1, "CreateDate")
workSheet.write(0, 2, "Created By")
workSheet.write(0, 3, "Storage Host Pathname")
workSheet.write(0, 4, "Storage Global Pathname")
workSheet.write(0, 5, "DB Schema Version")
workSheet.write(0, 6, "Mod_by_rem_user")
workSheet.write(0, 7, "Atomic Checkin")
workSheet.write(0, 8, "Owner user")
workSheet.write(0, 9, "Owner Group")
workSheet.write(0, 10, "ACLs enabled")
workSheet.write(0, 11, "FeatureLevel")
row = 0
entries = 0
fullentry = []
for linea in fp.readlines():
str_linea = linea.decode('gb2312', 'ignore')
str_linea = str_linea[:-2] # str string
txt = str_linea
arr = str_linea
if arr[:9] == "versioned":
txt = arr
entries += 1
s = txt.index("/")
e = txt.index('"', s)
txt = txt[s:e]
fullentry.append(txt)
elif arr.find("created") >= 0:
entries += 1
txt = arr
s = txt.index("created")
e = txt.index("by")
txt1 = txt[s + 7:20]
fullentry.append(txt1)
txt2 = txt[e + 3:]
fullentry.append(txt2)
elif arr.find("VOB storage host:pathname") >= 0:
entries += 1
txt = arr
s = txt.index('"')
e = txt.index('"', s + 1)
txt = txt[s + 1:e]
fullentry.append(txt)
elif arr.find("VOB storage global pathname") >= 0:
entries += 1
txt = arr
s = txt.index('"')
e = txt.index('"', s + 1)
txt = txt[s + 1:e]
fullentry.append(txt)
elif arr.find("database schema version:") >= 0:
entries += 1
txt = arr
txt = txt[-2:]
fullentry.append(txt)
elif arr.find("modification by remote privileged user:") >= 0:
entries += 1
txt = arr
s = txt.index(':')
txt = txt[s + 2:]
fullentry.append(txt)
elif arr.find("tomic checkin:") >= 0:
entries += 1
txt = arr
s = txt.index(':')
txt = txt[s + 2:]
fullentry.append(txt)
elif arr.find("owner ") >= 0:
entries += 1
txt = arr
s = txt.index('owner')
txt = txt[s + 5:]
fullentry.append(txt)
elif arr.find("group tmn") >= 0:
if arr.find("tmn/root") == -1:
entries += 1
txt = arr
s = txt.index('group')
entries += 1
txt = txt[s + 5:]
fullentry.append(txt)
elif arr.find("ACLs enabled:") >= 0:
entries += 1
txt = arr
txt = txt[-2:]
fullentry.append(txt)
elif arr.find("FeatureLevel =") >= 0:
entries += 1
txt = arr
txt = txt[-1:]
fullentry.append(txt)
if (row == 65536):
break;
finalarr = []
finalarr1 = []
temp = 0
row = 1
for r in fullentry:
finalarr.append(r)
temp += 1
if temp == 12:
finalarr1.append(finalarr)
temp = 0
col = 0
for arr in finalarr:
workSheet.write(row, col, arr)
col += 1
row += 1
finalarr.clear()
if (row == 65536):
break;
workBook.save(os.path.join(dest, "ClearcaseReport.xls"))
fp.close()
This is my file.txt datas(the file that script need to work and doesnt):
https://paste.pythondiscord.com/sedowagigo
This is how should output as excel file::
Details:
-The script that i did basically should read the datas inside the .txt file and based on the keywords that i put to create the columns and add the wanted datas in the right columns, but also should ignore the sh*t/raw datas dat dont need to be processed.
-First time was working thats why i have also the output photo .xls, but now its not working anymore because i added more datas inside and have more junkies... If someone can help me or you know other method im open to all
This is the old .txt file that i tested the script and works: https://paste.pythondiscord.com/ohewatahuv
This is the error that i received when i use the script on the new file that i attach inside the pastebin at the beggining ( https://paste.pythondiscord.com/sedowagigo ):
Ty for help!
I'm trying to get a list of backgrounds for each shots in an .xls document but I have no idea how to say to stop reading column and rows when it's a different shot...
The .xls I'm reading is like this:
and my test code is there:
import xlrd
planNameToFind = '002'
backgroundsList = []
openFolderPath = 'I:\\manue\\REFS\\516\\ALCM_516_SceneAssetList.xls'.format().replace('/','\\')
wb = xlrd.open_workbook(openFolderPath)
sheets = wb.sheet_by_index(0)
nrows = sheets.nrows
allcols = sheets.ncols
episode_index = 0
shot_index = 2
background_index = 9
rst = 1
seqrow = rst + 1
for rowx in xrange(rst + 2, nrows + 1):
planName = str(sheets.cell_value(seqrow, shot_index)).replace('.0', '')
if planName == planNameToFind:
print 'planName',planName
background = str(sheets.cell_value(seqrow, background_index)).replace('.0', '')
print 'background: ',background
backgroundsList.append(background)
if planName == '':
background = str(sheets.cell_value(seqrow, background_index)).replace('.0', '')
if background != '':
print 'background2: ',background
backgroundsList.append(background)
#shotToDo = ' shotToDo: {0} BG: {1}'.format(planName,background)
seqrow += 1
print 'backgroundsList: ',backgroundsList
My result log alls the backgrounds in the .xls, but I need only backgrounds of shot '002' (here only 3 backgrounds). Does someone know how to read backgrounds only for a shot?
Your best bet is to work with Panda Dataframes. It's extremely easy to clean data and work with it.
I am currently trying to loop through different excel files in a folder and amalgamate them into one main file. However, when trying to implement this loop I am getting the error Worksheet object is not callable.
Here is the code (apologies for my poor naming conventions):
import openpyxl
import openpyxl.formula
import pandas
import os
from openpyxl import Workbook
from openpyxl.styles import Alignment
from openpyxl.utils import get_column_letter
from openpyxl import load_workbook
from openpyxl import worksheet
#
# Declaration of openpyxl variables
#
directoryPath = "C:\\Users\\Desktop\\ExcelForReverse\\"
productionPath = "C:\\Users\\Desktop\\TransformedReverse.xlsx"
book_empty = Workbook()
book_empty.save(productionPath)
book_empty.create_sheet("Internals")
book_empty.create_sheet("Externals")
book_empty.create_sheet("All Formatted")
del_sheet = book_empty["Sheet"]
book_empty.remove_sheet(del_sheet)
book_empty.save(productionPath)
sheet_externals_con = book_empty["Externals"]
sheet_internals_con = book_empty["Internals"]
os.chdir(directoryPath)
folder_list = os.listdir(directoryPath)
attempt = 1
rowvar_externals = 2
rowvar_internals = 2
for folders, sub_folders, file in os.walk(directoryPath):
for name in file:
if name.endswith(".xlsx"):
filename = os.path.join(name)
print(filename)
wb_controller = load_workbook(filename, data_only=True)
sheet_controller_internals = wb_controller['Input INT']
sheet_controller_externals = wb_controller['Input EXT']
numOfRows_externals = sheet_controller_externals.max_row
numOfCols_externals = sheet_controller_externals.max_column
numOfRows_internals = sheet_controller_internals.max_row
numOfCols_internals = sheet_controller_internals.max_column
if attempt == 1:
for i in range(1,numOfCols_externals+1):
sheet_externals_con.cell(row = 1, column = i).value = sheet_controller_externals.cell(row = 3, column = i).value
for r in range(4,numOfRows_externals+1):
for i in range(1,numOfCols_externals+1):
sheet_externals_con.cell(row = rowvar_externals, column = i).value = sheet_controller_externals(row = r, column = i).value
rowvar_externals = rowvar_externals + 1
if attempt == 1:
for i in range(1,numOfCols_internals+1):
sheet_internals_con.cell(row = 1, column = i).value = sheet_controller_internals.cell(row = 3, column = i).value
for r in range(4,numOfRows_internals+1):
for i in range(1,numOfCols_internals+1):
sheet_internals_con.cell(row = rowvar_internals, column = i).value = sheet_controller_internals(row = r, column = i).value
rowvar_internals = rowvar_internals + 1
attempt = attempt + 1
print("Worked")
book_empty.save(productionPath)
The Error Message:
File line 48, in
sheet_externals_con.cell(row = rowvar_externals, column = i).value = sheet_controller_externals(row = r, column = i).value
builtins.TypeError: 'Worksheet' object is not callable
Should the line not read:
sheet_externals_con.cell(row = rowvar_externals, column = i).value = sheet_controller_externals.cell(row = r, column = i).value
Where
sheet_controller_externals -> sheet_controller_externals.cell
I am working on a VBA code which calls a python script saved at desktop. This is my piece of VBA code.
Shell "cmd /k C:\Python27\python.exe C:\Users\ashish.baboo\Desktop\UKT-SL-Ashish\Cleaning-Tools\Old-Geocode.py"
waitTill = Now() + TimeValue("00:00:40")
While Now() < waitTill
DoEvents
This Python script loads addresses in an excel file placed at desktop. When i run python script directly, It executes perfectly. But when i am running VBA code, Python script opens but gives me an error that excel file is not available. Here is my code of Python script:
import xlrd
import geocoder
import openpyxl
from openpyxl import load_workbook
location = "C:\\Users\\ashish.baboo\\Desktop\\UKT-SL-Ashish\\Cleaning-Tools\\1.xlsx"
workbook = xlrd.open_workbook(location)
sheet = workbook.sheet_by_index(1)
Rows = sheet.nrows
Cols = sheet.ncols
data = [[sheet.cell_value(r,c) for c in range(Cols)] for r in range(Rows)]
wb = load_workbook('1.xlsx')
ws1 = wb.get_sheet_by_name("Locations")
for i in range(1,Rows):
add = ws1.cell(row = i+1, column = 19).value
cadd = geocoder.google(add , language = "en" , key = "AIzaSyBsiH6LubuA9dn1s97UsUcesQRw71isBuo")
print(i , cadd.latlng , cadd.quality ,cadd.country)
S_no = ws1.cell(row = i+1, column = 1)
O_Housenumber = ws1.cell(row = i+1, column = 3)
O_Street = ws1.cell(row = i+1, column = 4)
O_City = ws1.cell(row = i+1, column = 5)
O_County = ws1.cell(row = i+1, column = 6)
O_State = ws1.cell(row = i+1, column = 7)
O_Postal = ws1.cell(row = i+1, column = 8)
O_Country = ws1.cell(row = i+1, column = 9)
Latitude = ws1.cell(row = i+1, column = 10)
Longitude = ws1.cell(row = i+1, column = 11)
Accuracy = ws1.cell(row = i+1, column = 12)
S_no.value = i
O_Housenumber.value = cadd.housenumber
O_Street.value = cadd.street
O_City.value = cadd.city
O_County.value = cadd.county
O_State.value = cadd.state_long
O_Postal.value = cadd.postal
O_Country.value = cadd.country_long
Latitude.value = cadd.lat
Longitude.value = cadd.lng
Accuracy.value = cadd.quality
wb.save('1.xlsx')
I already tried many solutions but was not successful. Kindly suggest how to resolve it ?
This line:
wb = load_workbook('1.xlsx')
relies on the program knowing where to look for the file. If you are firing up Python from VBA then the working directory will almost certainly be different. So your Python program needs to know the full filepath. You can either hard-code it in the program, or you can pass it in to the program from the command line.
use absolute path instead of relative path will do the trick!
I have imported xlrd etc. The main part of my code is then as follows:
for serie_diam in range(0,9):
namesheet = "Diamètre " + str(serie_diam)
#select(namesheet)
numLine = sh.row_values(3)
OK = 1
while OK == 1:
d = sh1(numLine, 1)
D = sh1(numLine, 2)
rs = sh1(numLine, 7)
for i in range(4):
BB = sh1(numLine, 2 + i)
if BB != 0:
print repr(d).rjust(2), repr(D).rjust(3), repr(B).rjust(4), repr(rs).rjust(5)
I have 7 sheets in my xls file overall and I would like to know how I can loop through these in the same while loop as OK == 1 where for the moment I have written just 'sh1'.
I'm sorry if this question is too easy!
import xlrd
book = xlrd.open_workbook('xlrd_test.xls')
for sheet in book.sheets():
print sheet.row(0) # do stuff here - I'm printing the first line as example
# or if you need the sheet index for some purpose:
for shidx in xrange(0, book.nsheets):
sheet = book.sheet_by_index(shidx)
# would print 'Page N, first line: ....'
print 'Page %d, first line: %s' % (shidx, sheet.row(0))