I'm trying to convert an excel file to xml using this skeleton code:
wb = load_workbook("deneme.xlsx")
# Getting an object of active sheet 1
ws = wb.worksheets[0]
doc, tag, text = Doc().tagtext()
xml_header = '<?xml version="1.0" encoding="UTF-8"?>'
# Appends the String to document
doc.asis(xml_header)
with tag('userdata'):
with tag('basicinf'):
for row in ws.iter_rows(min_row=2, max_row=None, min_col=1, max_col=90):
row = [cell.value for cell in row]
a=row[0]
with tag("usernumber"):
text(row[0])
with tag("username"):
text(row[1])
with tag("serviceareacode"):
text(row[2])
with tag("language"):
text(row[3])
with tag("welcomemsgid"):
text(row[4])
with tag("calledlimitedid"):
text(row[5])
with tag("followmeflag"):
text(row[6])
with tag("followmenumber"):
text(row[7])
with tag("mobilespecial"):
text(row[8])
result = indent(
doc.getvalue(),
indentation=' ',
indent_text=False
)
print(result)
with open("routescheme_{}.xml".format(a), "w") as f:
f.write(result)
Now if I don't write any input on row[0] in excel, I get the below error:
Traceback (most recent call last):
File "C:\Python39\lib\site-packages\yattag\simpledoc.py", line 489, in html_escape
return s.replace("&", "&").replace("<", "<").replace(">", ">")
AttributeError: 'NoneType' object has no attribute 'replace'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\abdul\Desktop\mmm\main.py", line 36, in <module>
text(row[0])
File "C:\Python39\lib\site-packages\yattag\simpledoc.py", line 179, in text
transformed_string = html_escape(strg)
File "C:\Python39\lib\site-packages\yattag\simpledoc.py", line 491, in html_escape
raise TypeError(
TypeError: You can only insert a string, an int or a float inside a xml/html text node. Got None (type <class 'NoneType'>) instead.
My expectation is that when row[0] is empty it should be like <usernumber></usernumber> in my xml result file.
How can I do that?
I guess ı found solution by myself. I am not sure this is a good solution but,
with tag("usernumber"):
if (row[0] == None):
text()
else:
text(row[0])
So if serviceare code is empty result is: <serviceareacode></serviceareacode>
if it is not empty, result is: <serviceareacode>value</serviceareacode>
Related
When i'm trying to fill the cell in existing .xlsx file and then save it to a new one I got message:
import openpyxl
path = "/home/karol/Dokumenty/wzor.xlsx"
wb_obj = openpyxl.load_workbook(path)
sheet_obj = wb_obj.active
new_protokol = sheet_obj
firma = input("Podaj nazwe: ")
nazwa_pliku = "Protokol odczytu"
filename = nazwa_pliku + firma + ".xlsx"
sheet_obj["C1"] = firma
sheet_obj["D1"] = input()
new_protokol.save(filename=filename)
Traceback (most recent call last):
File "/home/karol/PycharmProjects/Protokolu/Main.py", line 16, in <module>
sheet_obj["C1"] = firma
File "/home/karol/PycharmProjects/Protokolu/venv/lib/python3.7/site-packages/openpyxl/worksheet/worksheet.py", line 309, in __setitem__
self[key].value = value
AttributeError: 'MergedCell' object attribute 'value' is read-only
Process finished with exit code 1
How to fix it?
When you merge cells all cells but the top-left one are removed from the worksheet. To carry the border-information of the merged cell, the boundary cells of the merged cell are created as MergeCells which always have the value 'None'
ws.merge_cells('B2:F4')
top_left_cell = ws['B2']
top_left_cell.value = "My Cell"
Please try this approach, it'll work just fine for you.
To write in a merge cell, you must write in the cell in the upper left corner. And the error will not come out.
ws['I6']="123123123"
wb.save(filename=path....)
I also met this error. I deleted my current Excel file and replaced it with a good Excel file, and then the error disappeared.
I am trying to run through an excel file line by line and create a new list and then append every cell value on that line to the list. I don't think my code is correct but I just want to know why it cannot find the file, this is the error message.
def createPersonList(fileName):
open(fileName)
i = 0.0
for line in fileName:
i += 1
Person = []
for cell in line:
Person.append(cell)
return Person
error message:
createPersonList(personData.csv) Traceback (most recent call last):
File "<ipython-input-36-207031458d64>", line 1, in <module>
createPersonList(personData.csv) NameError: name 'personData' is not defined
I don't understand very well what you want, and also i don't know your structure of file.
But that's something similar with what you want:
import csv
def createPersonList(fileName):
personList = []
with open(fileName, 'r') as csv_file:
csv_reader = csv.reader(csv_file, delimiter='\t')
next(csv_reader, None)
for row in csv_reader:
for column in row:
personList.append(column)
return personList
Hello all I keep getting this error while making a small program to sort large CSV files out, below is my code and error, what am I doing wrong?
if selection:
for stuff in stuffs:
try:
textFile = open("output.txt",'w')
mycsv = csv.reader(open(stuff))
d_reader = csv.DictReader(mycsv)
headers = d_reader.fieldnames <-- Error happens here
if selection in headers:
placeInList = headers.index(selection)
#placeInList = selection.index(selection)
for selection in tqdm(mycsv, desc='Extracting column values...', leave = True):
textFile.write(str(selection[int(placeInList)])+'\n')
print 'Done!'
textFile.close()
sys.exit()
except IOError:
print 'No CSV file present in directory'
sys.exit()
else:
sys.exit()
And the error:
Traceback (most recent call last):
File "postcodeExtractor.py", line 27, in <module> headers = d_reader.fieldnames
File "C:\Python27\lib\csv.py", line 90, in fieldnames self._fieldnames = self.reader.next()
TypeError: expected string or Unicode object, list found
instead of
mycsv = csv.reader(open(stuff))
d_reader = csv.DictReader(mycsv)
you want
d_reader = csv.DictReader(open(stuff))
the first line is the problem.
I have a query that's grabbing data from a database and returning the values so I can parse.
def executeScriptsFromFile(monitor):
# Open and read the file as a single buffer
fd = open(os.path.join(BASE_DIR, 'sql/{0}.sql'.format(monitor)), 'r')
if args.alias:
sql_query = fd.read().format("'" + args.alias + "'")
else:
sql_query = fd.read()
fd.close()
# Execute SQL query from the input file
cursor.execute(sql_query)
result = cursor.fetchone()
return result
The query can differ so I'm trying to build in logic so it will skip part if JobCount isn't one of the values.
query_data = executeScriptsFromFile(args.monitor)
print query_data
if query_data.JobCount:
print query_data.JobCount
else:
send_status = send_data(job_data)
print send_status
Unfortunately I get the following traceback. How do I ignore the value if it isn't there?
Traceback (most recent call last):
File "tidal-zabbix.py", line 92, in <module>
if query_data.JobCount:
AttributeError: 'pyodbc.Row' object has no attribute 'JobCount'
If you want to check whether 'JobCount' is an attribute of query_data use hasattr()
if hasattr(query_data, 'JobCount'):
print query_data.JobCount
else:
send_status = send_data(job_data)
print send_status
I have an .xls file which contains one column with 2,000 rows.
I want to iterate through the file and print out the data points
which start with "cheap". However, the following code doesn't work.
Help!
import xlrd
wb = xlrd.open_workbook("file.xls")
wb.sheet_names()
sh = wb.sheet_by_index(0)
lst = [sh]
for item in lst:
print item.startswith("cheap")
Traceback (most recent call last):
File "C:\Python26\keywords.py", line 14, in <module>
print item.startswith("cheap")
AttributeError: 'Sheet' object has no attribute 'startswith'
it should look like:
import xlrd
wb = xlrd.open_workbook("file.xls")
wb.sheet_names()
sh = wb.sheet_by_index(0)
for item in sh.col(0):
value = unicode(item.value)
if value.startswith("cheap"):
print value