For the past day i've been trying to get openpyxl or any other python excel library to read the cell value. But every time i run the program it returns with None if i set it to data_only = True. If i dont add the data_only it only returns the formula im using. This is my code:
wb = xl.load_workbook(str(tm.strftime("%d-%m-%Y")) + ' - ' + str(tm.strftime("%A")) + '.xlsx')
ws = wb.active
bag = float(self.entryBags.get())
ws['B3'] = bag
wb.save(str(tm.strftime("%d-%m-%Y")) + ' - ' + str(tm.strftime("%A")) + '.xlsx')
wb2 = xl.load_workbook(str(tm.strftime("%d-%m-%Y")) + ' - ' + str(tm.strftime("%A")) + '.xlsx', data_only = True)
ws2 = wb2.active
total_till = ws2['B13']
print(total_till.value)
If any one can give any suggestions on how to read the cell value, using openpyxl or any other python library, it would be very helpful.
Thanks
Related
I have a bunch of files and I'm running a loop to do some calculations. This loop is already done, but I am saving the results to new files, according to the original one.
file1.xlsx
file2.xlsx
after running the code:
results/file1_results.xlsx
results/file2_results.xlsx
This is the loop through files:
directory = os.getcwd()
for filename in os.listdir(directory):
if filename.endswith(".xlsx"):
wb = load_workbook(filename)
ws = wb.active
max_row = ws.max_row
ws["CX1"] = "Humanas"
for row in range(2, max_row + 1):
ws["CX{}".format(row)] = round((
ws['R{}'.format(row)].value +
ws['U{}'.format(row)].value +
ws['X{}'.format(row)].value +
ws['AA{}'.format(row)].value +
ws['AD{}'.format(row)].value +
ws['AG{}'.format(row)].value +
ws['AJ{}'.format(row)].value +
ws['AM{}'.format(row)].value ) * (50/8))
ws["CY1"] = "Exatas"
for row in range(2, max_row + 1):
ws["CY{}".format(row)] = round((
ws['AP{}'.format(row)].value +
ws['AS{}'.format(row)].value +
ws['AV{}'.format(row)].value +
ws['AY{}'.format(row)].value ) * (50/4))
ws["CZ1"] = "Linguagens"
for row in range(2, max_row + 1):
ws["CZ{}".format(row)] = round((
ws['BB{}'.format(row)].value +
ws['BE{}'.format(row)].value +
ws['BH{}'.format(row)].value +
ws['BK{}'.format(row)].value +
ws['BN{}'.format(row)].value +
ws['BQ{}'.format(row)].value +
ws['BT{}'.format(row)].value +
ws['BW{}'.format(row)].value +
ws['BZ{}'.format(row)].value +
ws['CC{}'.format(row)].value +
ws['CF{}'.format(row)].value +
ws['CI{}'.format(row)].value ) * (50/12))
ws["DA1"] = "Biológicas"
for row in range(2, max_row + 1):
ws["DA{}".format(row)] = round((
ws['CL{}'.format(row)].value +
ws['CO{}'.format(row)].value +
ws['CR{}'.format(row)].value +
ws['CU{}'.format(row)].value ) * (50/4))
wb.save('results/' + os.path.splitext(filename)[0] + '_results.xlsx')
wb.close
else:
continue
The data is a bunch of dummies (0 or 1)
I need to adjust the results to a single file.xlsx.
I need to get multiple worksheets(named as original files or close to this).
I don't want to merge into a single ws
I am trying to copy the range of all results.xlsx and place into the new file. But no success.
A good alternative could be skip the creation of all files and place results directly into the final one, but I can not figure how to do this.
Edit 1 - Got success of joining all of results in specific worksheet, but now, I need to clean up all of them to get only the results.
dest_wb = Workbook()
from openpyxl import Workbook
from openpyxl import load_workbook
for root, dir, filenames in os.walk(path):
for file in filenames:
file_name = file.split('.')[0]
file_path = os.path.abspath(os.path.join(root, file))
# Create new sheet in destination Workbook
dest_wb.create_sheet(file_name)
dest_ws = dest_wb[file_name]
source_wb = load_workbook(file_path)
source_sheet = source_wb.active
for row in source_sheet.rows:
for cell in row:
dest_ws[cell.coordinate] = cell.value
dest_wb.save("results/report.xlsx")
Did this to the results:
dados = pd.read_excel("results/report.xlsx", sheet_name=None)
df = pd.concat(dados[frame] for frame in dados.keys())
lista_colunas = [7, 10, 101, 102, 103, 104]
filtro = df.columns[lista_colunas]
final_df = df[filtro]
grouped_df = final_df.groupby(final_df.columns[1])
salas = grouped_df.groups.keys()
writer = pd.ExcelWriter('results/resultado.xlsx', engine='xlsxwriter')
for sala in salas:
splitdf = grouped_df.get_group(sala)
splitdf.to_excel(writer, sheet_name=str(sala))
writer.save()
I am fairly new to python and trying to copy the data in workbook one, columns A,D,G, paste them into columns A,B,C, on the new workbook. I know how to copy one column or the whole worksheet but can't figure that out.
from openpyxl import load_workbook
wb1 = load_workbook('test1.xlsx')
wb2 = load_workbook('test2.xlsx')
ws1 = wb1.get_sheet_by_name('Sheet1')
ws2 = wb2.get_sheet_by_name('Sheet1')
mr = ws1.max_row
mc = ws1.max_column
for i in range (1, mr + 1):
for j in range (1, mc + 1):
c = ws1.cell(row=i, column=j)
ws2.cell(row=i, column=j).value = c.value
wb2.save('test2.xlsx')
That is the code I am using to copy the whole worksheet
I think you're looking for something like this
for i in range(1, mr + 1):
ws2['A' + str(i)].value = ws1['A' + str(i)].value
ws2['B' + str(i)].value = ws1['D' + str(i)].value
ws2['C' + str(i)].value = ws1['G' + str(i)].value
I'm using xlwings to open excel sheet. Need to search a string in a specific column and print full line of the string without search item and until new line(\n). Output should be in new column of same sheet.
Input:
search string: [game]
Output:
import xlwings as xw
open excel file using xlwings
filename = r'input.xlsx'
book = xw.Book(filename)
sheet = book.sheets[0]
find the last row of the sheet on a specific range in this case from column 'A'
lrow = sheet.range('A' + str(sheet.cells.last_cell.row)).end('up').row
declare a separate variable for the string that you will search and the column where your output will be located.
search_string = '[game]'
sheet.range('B1').value = 'output'
output_index = 2
now loop through that range to see if your search_string is in that range
for i in range(1, lrow + 1):
if search_string in str(sheet.range('A{}'.format(i)).value):
temp = str(sheet.range('A{}'.format(i)).value)
temp = temp.split(search_string)[1]
if '[' in temp:
temp = temp.split('[')[0]
sheet.range('B{}'.format(output_index)).value = temp
output_index += 1
book.save()
book.close()
Below is the full code >>
import xlwings as xw
filename = r'input.xlsx'
book = xw.Book(filename)
sheet = book.sheets[0]
lrow = sheet.range('A' + str(sheet.cells.last_cell.row)).end('up').row
search_string = '[game]'
sheet.range('B1').value = 'output'
output_index = 2
for i in range(1, lrow + 1):
if search_string in str(sheet.range('A{}'.format(i)).value):
temp = str(sheet.range('A{}'.format(i)).value)
temp = temp.split(search_string)[1]
if '[' in temp:
temp = temp.split('[')[0]
sheet.range('B{}'.format(output_index)).value = temp
output_index += 1
book.save()
book.close()
I am now working on combining data for 2 excel file. my approach is to use xlwt to create a new excel and corresponding sheet. and then use for loop to write into the newly created excel file. my code is as below,
#......
wbk = xlwt.Workbook()
sheet_0 = wbk.add_sheet('A')
sheet_1 = wbk.add_sheet('B')
wbk.save(os.path.join(currentPath, gsheet.cell(gsr, 2).value) + FullName + " " + time_now + ".xls")
wkbk = xlrd.open_workbook(
os.path.join(currentPath, gsheet.cell(gsr, 2).value) + FullName + " " + time_now + ".xls")
wb_merge = copy(wkbk)
wsheet_0 = wb_merge.get_sheet(0)
wsheet_1 = wb_merge.get_sheet(1)
workbook_merge_0 = xlrd.open_workbook(os.path.join(currentPath, filename0), formatting_info=True)
sheet_merge_0 = workbook_merge_0.sheet_by_index(0)
for r in range(0, total_row_0):
for c in range(0, total_col_0):
wsheet_1.write(r, c, sheet_merge_0(r, c).value)
#......
when i am running the whole code, error show TypeError: 'Sheet' object is not callable, pointing to the last row, i.e. wsheet_1.write(r, c, sheet_merge_0(r, c).value)
Any suggestion can be provided? Thanks in advance!
I am attempting to clean up an excel file and essentially what I want to do is this: I have inserted a formula in column B that references column A and would like to then take all the values in column B and paste special as values over column A. After, I would like to delete column B.
Does anyone know of anyway to do this via openpyxl library or another library?
Here is a copy of my code thus far:
import openpyxl as xl
import pandas as pd
import datetime as dt
import os
def left(s, amount):
return s[:amount]
def right(s, amount):
return s[-amount:]
def mid(s, offset, amount):
return s[offset:offset+amount]
filepath = r'...desktop\Scripts' + '\\'
filename = 'file.xlsx'
fn = filepath + filename
WB = xl.load_workbook(fn, data_only = True)
WS = WB.worksheets[1]
for i in sorted(WS.merged_cell_ranges):
WS.unmerge_cells(str(i))
WB.save(filepath + 'unmerged.xlsx')
unmerged = pd.read_excel(filepath + 'unmerged.xlsx', sheetname = 1)
unmerged.insert(1, 'ifIsBlank', '')
unmerged.insert(5, 'trimSubst', '')
inserted = unmerged.to_excel(filepath + 'inserted.xlsx', index = False)
WB = xl.load_workbook(filepath + 'inserted.xlsx')
WS = WB.worksheets[0]
WS['A'][0].value = 'BU'
WS['E'][0].value = 'em name'
blankCount1 = 1
blankCount2 = 0
trimCount = 1
for i, cell in enumerate(WS['B']):
cell.value = '=IF(ISBLANK(A' + str(blankCount1) + '), B' + str(blankCount2) + ', A' + str(blankCount1) + ')'.format(i)
blankCount1 += 1
blankCount2 += 1
for j, cell in enumerate(WS['F']):
cell.value = '=TRIM(SUBSTITUTE(E' + str(trimCount) + ', "~", "_"))'.format(j)
trimCount += 1
WS['B'][0].value = 'Category Name'
WS['F'][0].value = 'Item Name'
WB.save(filepath + 'formula.xlsx')
valWB = xl.load_workbook(filepath + 'formula.xlsx', data_only = True)
So the issue I'm running into is that when I read formula.xlsx as a .csv (desired file type of my final output), it shows nothing in the cells that have the formula- Is there a way to essentially copy and paste the values that come out of the formula into another column?
Thanks!