Printing whole row from excel with pandas or something else? - python

Hello i need some help i try to do this abouth 2hours i was looking on internet but i couldnt find any solution,
i want from excel to print horizontal row from name that i found
here is picture what i want to print https://imgur.com/a/lZduGCV
elif "name " in data:
baza = pd.read_excel('Baza.xlsx')
data = data.split(" ")
name = data[1]
botgovor("Hold a second.I will check data base for that name")
for name in baza:
botgovor("We have that name in database,What would you like to do with it?")
data = covekgovor()
robot(data)
if "check it" in data:
informacije = pd.read_excel('Baza.xlsx')
botgovor(informacije)

import xlrd
loc = ("excel_file.xlsx") # excel file name
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)
search_name = "Landon"
for i in range(sheet.nrows):
if search_name == sheet.cell_value(i, 0):
print(sheet.row_values(i))

Related

How to save an excel workbook from within python

I'm new to python I made this code which makes you input data that is Automatticly inputted into excel.
The thing is when I run the program twice it overwrites the previous data so I need to know how to save it.
this is the code I wrote
import xlsxwriter
workbook = xlsxwriter.Workbook('Book1.xlsx')
worksheet = workbook.add_worksheet()
name = input('your full name: ')
age = int(input('your age: '))
emaill = input('your email: ')
idontknow = (
['Name', name],
['Age', age],
['Email', emaill],
)
row = 0
col = 0
for item, cost in idontknow:
worksheet.write(row, col, item)
worksheet.write(row, col + 1, cost)
row += 1
workbook.close()
any suggestion will help
I would recommend using the pandas library to perform the data manipulation. A code that performs the task you indicate would be the following:
import pandas as pd
#read the file and make a DataFrame
data = pd.read_excel('Book1.xlsx')
df = pd.DataFrame(data)
#get the data
name = input('your full name: ')
age = int(input('your age: '))
email = input('your email: ')
#get the last edited row
row = len(df)
#write the data
df.loc[row, 'name'] = name
df.loc[row, 'age'] = age
df.loc[row, 'email'] = email
#save the file
df.to_excel('Book1.xlsx',index=False)
Additionally, this code allows you to have headers for each column in your file, which is convenient in most situations.
I would recommend using "csv" - https://docs.python.org/3/library/csv.html
excel can read and save to csv format, and I find it easier to work with.
openpyxl provide more functionality in parsing excel files, with similar syntax as xlsxwriter. (worksheet.max_row for example is accessible in openpyxl but not in xlsxwriter)
import openpyxl
workbook = openpyxl.load_workbook('Book1.xlsx')
worksheet = workbook.create_sheet(0)
name = input('your full name: ')
age = int(input('your age: '))
emaill = input('your email: ')
idontknow = (
['Name', name],
['Age', age],
['Email', emaill],
)
row = worksheet.max_row + 1
for item, cost in idontknow:
worksheet.cell(row=row, column=0, value=item)
worksheet.cell(row=row, column=1, value=cost)
row += 1
workbook.save('Book1.xlsx')

Is there a way to move the rows of all the sheets to specific row number using Openpyxl in Python?

I am using Openpyxl to read the excel file and get my desired output in txt file (not all the code shown below as it is irrelevant). Below is my code for reading the excel file.The test file contains 3 sheets.As you might have noticed, I am skipping 1st sheet in my excel file.The other sheets has the data that I need. The Columns that I am interested in are "Field Name" and "Type". However, as shown in below snippets, the rows are located in row 5 in sheet 1 and row 8 in sheet 2. I was wondering if I can get both sheets to have "Field Name" and "Type" to start from 7 (instead of doing manually) ? Is there any search that I can perform to make sure that I have "Field Name" and "Type" on row 7, if not can I have it corrected in the same sheet instead of creating a copy the sheet ? I checked here, unfortunately couldn't find the solution. The reason to start from row 7 is because I am taking the data from row8 onwards form the sheet and adding it to txt file.
Note: Below snapshots are demo only. My original excel file contains 10+ sheets with same issue i.e. "Field Name" and "Type" not starting from row 7
Thanks in advance for your help!
Python code:
from openpyxl import load_workbook
data_file='test.xlsx'
# Load the entire workbook.
wb = load_workbook(data_file)
skip = True
for ws in wb.worksheets:
if skip == True:
skip = False
else:
for i in range(7, ws.max_row+1):
name = ws.cell(row=i, column=1).value
print(i, name)
name1=ws.cell(row=i, column=2).value
print(name1)
....... my other code
Sheet 1
Sheet 2:
Sheet output after SO comments:
Sheet 1:
Sheet 2:
You can achieve this by using insert_rows() and delete_rows()...
Note that you need to save the file once you have added/deleted the rows.
from openpyxl import load_workbook
data_file='test.xlsx'
# Load the entire workbook.
wb = load_workbook(data_file)
skip = True
for ws in wb.worksheets:
if skip == True:
skip = False
else:
CurrentRow = 0
for row in ws.iter_rows(max_col=2):
if row[0].value == 'Field Name' and row[1].value == 'Type':
CurrentRow = row[0].row
break
else:
pass
if CurrentRow > 7:
ws.delete_rows(7, CurrentRow - 7)
elif CurrentRow < 7 and CurrentRow > 0:
ws.insert_rows(CurrentRow, 7 - CurrentRow)
wb.save('test.xlsx')
Dealing with tables
It looks like the input data in your sheet is a excel Table. You can check this by selecting the range and right-clicking (should have table option under Quick Analysis). If this is the case, you have two options.
Select a cell in table >> right click >> Table >> Convert to Range. Then the original code will run. Don't know if that works.
Written below is the code that will work if all your sheets have tables. Note that I am considering that there is only one table in each sheet. Also, the style is set to the blue format you have shared in your pics above. Borrowed code from here
from openpyxl import load_workbook
from openpyxl.worksheet.table import Table, TableStyleInfo
style = TableStyleInfo(name="TableStyleMedium9", showFirstColumn=False, showLastColumn=False, showRowStripes=True, showColumnStripes=False)
def colnum_string(n):
string = ""
while n > 0:
n, remainder = divmod(n - 1, 26)
string = chr(65 + remainder) + string
return string
#data_file='test.xlsx'
data_file = input("Please provide the name of file you want to process: ")
# Load the entire workbook.
wb = load_workbook(data_file)
skip = True
for ws in wb.worksheets:
if skip == True:
skip = False
else:
CurrentRow = 0
tablelen = 0
for row in ws.iter_rows(max_col=2):
if row[0].value == 'Field Name' and row[1].value == 'Type':
CurrentRow = row[0].row
tablelen = ws.max_row - CurrentRow
break
else:
pass
if CurrentRow > 7:
ws.delete_rows(7, CurrentRow - 7)
resTable = Table(displayName=ws.tables.items()[0][0], ref="A7:{}{}".format("B", 7+tablelen))
resTable.tableStyleInfo = style
ws._tables[ws.tables.items()[0][0]] = resTable
elif CurrentRow < 7 and CurrentRow > 0:
ws.insert_rows(CurrentRow, 7 - CurrentRow)
resTable = Table(displayName=ws.tables.items()[0][0], ref="A7:{}{}".format("B", 7+tablelen))
resTable.tableStyleInfo = style
ws._tables[ws.tables.items()[0][0]] = resTable
#wb.save('test.xlsx')
wb.save(data_file.split('.')[0] + "_updated." + data_file.split('.')[1])
New Req - Read all xlsx files
from openpyxl import load_workbook
from openpyxl.worksheet.table import Table, TableStyleInfo
style = TableStyleInfo(name="TableStyleMedium9", showFirstColumn=False, showLastColumn=False, showRowStripes=True, showColumnStripes=False)
def colnum_string(n):
string = ""
while n > 0:
n, remainder = divmod(n - 1, 26)
string = chr(65 + remainder) + string
return string
import os
ALLOWED_EXTENSIONS = set(['xlsx'])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
MyPWD = os.getcwd()
for filename in os.listdir(MyPWD):
path = os.path.join(MyPWD, filename)
if os.path.isfile(path) and allowed_file(filename):
#data_file='test1.xlsx'
#data_file = input("Please provide the name of file you want to process: ")
# Load the entire workbook.
wb = load_workbook(filename)
skip = True
for ws in wb.worksheets:
if skip == True:
skip = False
else:
CurrentRow = 0
tablelen = 0
for row in ws.iter_rows(max_col=2):
if row[0].value == 'Field Name' and row[1].value == 'Type':
CurrentRow = row[0].row
tablelen = ws.max_row - CurrentRow
break
else:
pass
if CurrentRow > 7:
ws.delete_rows(7, CurrentRow - 7)
resTable = Table(displayName=ws.tables.items()[0][0], ref="A7:{}{}".format("B", 7+tablelen))
resTable.tableStyleInfo = style
ws._tables[ws.tables.items()[0][0]] = resTable
elif CurrentRow < 7 and CurrentRow > 0:
ws.insert_rows(CurrentRow, 7 - CurrentRow)
resTable = Table(displayName=ws.tables.items()[0][0], ref="A7:{}{}".format("B", 7+tablelen))
resTable.tableStyleInfo = style
ws._tables[ws.tables.items()[0][0]] = resTable
#wb.save('test2.xlsx')
wb.save(filename.split('.')[0] + "_updated." + filename.split('.')[1])

how to save the data entered in the textbox in excel using openpyxl

i made a program that will input the invoice number and search the excel file(ref my previous question : How to extract a particular row value on inputting value of a particular row),
now i want to save the data fetched by the program into a new excel file using openpyxl,
but i dont know what is the solution to this,
i am using python 3.7.0.
my code is
from tkinter import *
import openpyxl
def update_text(info):
book_info.delete(1.0, 'end')
book_info.insert('end', info)
def find_book():
inv_no = inv_field.get()
if inv_no:
wb = openpyxl.load_workbook('E:\Library Management\issue.xlsx')
sheet = wb.active
for row in sheet.rows:
# assume invoice no is in column 1
if row[0].value == inv_no:
update_text('\n'.join(str(cell.value) if cell.value else '' for cell in row))
return
wb.close()
update_text('Book not found')
a = Tk()
a.title('Return Book')
a.geometry('500x200')
heading = Label(a,text = 'Return Book')
heading.grid(row = 0,column = 1)
lab1 = Label(a,text = 'Enter Invoice Number:')
lab1.grid(row = 1, column = 0)
inv_field = Entry(a)
inv_field.grid(row = 1, column = 1)
inv_field.get()
find = Button(a,text = 'Find',width = 4,command =find_book)
find.grid(row = 2, column = 1)
book_info = Text(a, width=40, height=5)
book_info.grid(row = 3 ,column = 1)
a.mainloop()
how can i do this and how can i save the data displayed ,in a new excel file
You can create another workbook and write the result into the active sheet. Then save the workbook to file. Below is an sample code:
outwb = openpyxl.Workbook()
ws = outwb.active
ws.append([1, 2, 3, 4])
outwb.save('result.xlsx')
outwb.close()
I am not sure how it is done in openpyxl, but in xlwt it is .save(). Try running a print(help(wb)), should tell you all submethods on that object.

Transfering specific rows from one cvs file to another cvs file

So, I'm trying to transfer rows[0,1,2,9,10] from what I've designated as "e_file" to "no_file"
When I print "data" I am given the exact information I want, I was just wondering how I should proceed with transferring this data to a corresponding CSV file?
Thank you.
e_file = '/Users/massive/Desktop//NO/hour.csv'
no_file = '/Users/massive/Desktop/NO/combined.csv'
with open(e_file,'r') as e_r:
state_code = input("Enter state code: ")
county_code = input("Enter county code: ")
station_number = input("Enter station number: ")
csv_reader_2 = csv.reader(e_r)
for row in csv_reader_2:
if row[0] == str(state_code).zfill(2) and row[1] ==str(county_code).zfill(3) and row[2] == str(station_number).zfill(4):
data = [row[0],row[1],row[2],row[9],row[10]]
print(data)
Maybe something like (I cannot test it unless you provide a working example):
with open(newFile, 'wb') as csvfile:
fwriter = csv.writer(csvfile)
for line in data:
fwriter.writerow(line)

Txt file to excel conversion in python

I'm trying to convert text file to excel sheet in python. The txt file contains data in the below specified formart
Column names: reg no, zip code, loc id, emp id, lastname, first name. Each record has one or more error numbers. Each record have their column names listed above the values. I would like to create an excel sheet containing reg no, firstname, lastname and errors listed in separate rows for each record.
How can I put the records in excel sheet ? Should I be using regular expressions ? And how can I insert error numbers in different rows for that corresponding record?
Expected output:
Here is the link to the input file:
https://github.com/trEaSRE124/Text_Excel_python/blob/master/new.txt
Any code snippets or suggestions are kindly appreciated.
Here is a draft code. Let me know if any changes needed:
# import pandas as pd
from collections import OrderedDict
from datetime import date
import csv
with open('in.txt') as f:
with open('out.csv', 'wb') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
#Remove inital clutter
while("INPUT DATA" not in f.readline()):
continue
header = ["REG NO", "ZIP CODE", "LOC ID", "EMP ID", "LASTNAME", "FIRSTNAME", "ERROR"]; data = list(); errors = list()
spamwriter.writerow(header)
print header
while(True):
line = f.readline()
errors = list()
if("END" in line):
exit()
try:
int(line.split()[0])
data = line.strip().split()
f.readline() # get rid of \n
line = f.readline()
while("ERROR" in line):
errors.append(line.strip())
line = f.readline()
spamwriter.writerow(data + errors)
spamwriter.flush()
except:
continue
# while(True):
# line = f.readline()
Use python-2 to run. The errors are appended as subsequent columns. It's slightly complicated the way you want it. I can fix it if still needed
Output looks like:
You can do this using the openpyxl library which is capable of depositing items directly into a spreadsheet. This code shows how to do that for your particular situation.
NEW_PERSON, ERROR_LINE = 1,2
def Line_items():
with open('katherine.txt') as katherine:
for line in katherine:
line = line.strip()
if not line:
continue
items = line.split()
if items[0].isnumeric():
yield NEW_PERSON, items
elif items[:2] == ['ERROR', 'NUM']:
yield ERROR_LINE, line
else:
continue
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws['A2'] = 'REG NO'
ws['B2'] = 'LASTNAME'
ws['C2'] = 'FIRSTNAME'
ws['D2'] = 'ERROR'
row = 2
for kind, data in Line_items():
if kind == NEW_PERSON:
row += 2
ws['A{:d}'.format(row)] = int(data[0])
ws['B{:d}'.format(row)] = data[-2]
ws['C{:d}'.format(row)] = data[-1]
first = True
else:
if first:
first = False
else:
row += 1
ws['D{:d}'.format(row)] = data
wb.save(filename='katherine.xlsx')
This is a screen snapshot of the result.

Categories

Resources