I'm trying to extract my data into Excel, but I'm having a problem
in this part:
sheet.cell(row=i+2, column=7).value = OeFC1b.value
So I use print() and check the value. It is 50.20042375032.
I get this error message:
raise ValueError("Cannot convert {0!r} to Excel".format(value))
ValueError: Cannot convert array(50.20042375) to Excel
Why is it an array and how do I extract that data?
Here is the whole code:
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 16 18:18:01 2022
#author: mskim
"""
import pandas as pd
import cvxpy as cp
import numpy as np
import openpyxl
Demand_Excel = pd.read_excel('Input/Demands.xlsx',index_col=0)
data = pd.DataFrame(Demand_Excel)
wb = openpyxl.Workbook()
sheet = wb.active
sheet.cell(row=1, column=1).value = "총 수익"
sheet.cell(row=1, column=2).value = "그리드 판매 수익"
sheet.cell(row=1, column=3).value = "연료 가격"
sheet.cell(row=1, column=4).value = "건물 전기 절약값"
sheet.cell(row=1, column=5).value = "난방비 판매값"
sheet.cell(row=1, column=6).value = "전기차 전기 절약값"
sheet.cell(row=1, column=7).value = "수소차 탱크 절약값"
sheet.cell(row=1, column=8).value = "FC1 그리드 판매량"
sheet.cell(row=1, column=9).value = "FC1 건물 사용량"
sheet.cell(row=1, column=10).value = "FC1 전기차 사용량"
sheet.cell(row=1, column=11).value = "FC2 발전량"
sheet.cell(row=1, column=12).value = "CHP 발전량"
sheet.cell(row=1, column=13).value = "PV 그리드 판매량"
sheet.cell(row=1, column=14).value = "PV 건물 사용량"
sheet.cell(row=1, column=15).value = "PV 전기차 사용량"
#sheet.cell(row=1, column=1).value = ""
for i in range(0,2): # Time Regulation (0,8759)
OeFC1g = cp.Variable()
OeFC1b = cp.Variable()
OeFC1e = cp.Variable()
OeFC2 = cp.Variable()
OeCHP = cp.Variable()
OePVg = cp.Variable()
OePVb = cp.Variable()
OePVe = cp.Variable()
BD = np.array(data.iloc[[i],[0]])
EV = np.array(data.iloc[[i],[1]])
HD = np.array(data.iloc[[i],[2]])
PFC1 = 9.33863636
PFC2 = 12.94857
PCHP = 14.22143
hFC1 = 0.50818182
hFC2 = 0.393143
hCHP = 2.297429
HFC2 = 0.025714
PGAS = 19.3870
PP = np.array(data.iloc[[i],[3]])
heat=396.76
Hprice=8000
constraints = [
0<=OeFC1g,
OeFC1g<=440,
0<=OeFC1b,
OeFC1b<=440,
0<=OeFC1e,
OeFC1e<=440,
OeFC1g + OeFC1b + OeFC1e <= 440,
0<=OePVg,
OePVg<=50,
0<=OePVb,
OePVb<=50,
0<=OePVe,
OePVe<=50,
OePVg + OePVb + OePVe == 50,
0<=OeFC2,
OeFC2<=350,
0<=OeCHP,
OeCHP<=140,
OeFC1b + OePVb == BD,
OeFC1e + OePVe == EV
]
# Korean Money Unit Won
heat_profit = ((OeFC1e + OeFC1g + OeFC1b) * hFC1 + OeFC2 * hFC2 +OeCHP * hCHP) * heat
Power_sell = PP * (OeFC2 + OeCHP + OeFC1g + OePVg )
Fuel_Price = ((OeFC1e + OeFC1g + OeFC1b) * PFC1 + OeFC2 * PFC2 +OeCHP * PCHP) * PGAS
Building_profit = BD * 100 + 6160 # 100 is buying price for electric power, other is base price
EV_profit = EV*100 + 2390 # 100 is buying price for electric power, other is base price
H2_profit = Hprice * ( OeFC2 * HFC2 - HD) # We have H2 tanks
obj = cp.Maximize( Power_sell - Fuel_Price + EV_profit + H2_profit + Building_profit + heat_profit )
prob = cp.Problem(obj, constraints)
prob.solve()
sheet = wb.active
print(OeFC1b.value)
sheet.cell(row=i+2, column=1).value = obj.value
sheet.cell(row=i+2, column=2).value = Power_sell[0][0].value
sheet.cell(row=i+2, column=3).value = Fuel_Price.value
sheet.cell(row=i+2, column=4).value = Building_profit[0][0]
sheet.cell(row=i+2, column=5).value = heat_profit.value
sheet.cell(row=i+2, column=6).value = EV_profit[0][0]
sheet.cell(row=i+2, column=7).value = H2_profit[0][0].value
sheet.cell(row=i+2, column=7).value = OeFC1b.value #error
# sheet.cell(row=i+2, column=10).value = OeFC2.value
wb.save('Output/test_for_excel.xlsx')
Im not familiar with the cvxpy lib but i belive you are trying to write a list to the excel document. I don't think that is supported.
This code produce a similar error
import openpyxl
val = [50.20042375]
wb = openpyxl.Workbook()
sheet = wb.active
sheet.cell(row=1, column=1).value = val
To fix the issue do add a [0] in the end like this
import openpyxl
val = [50.20042375]
wb = openpyxl.Workbook()
sheet = wb.active
sheet.cell(row=1, column=1).value = val[0]
Related
I've written a script which copies data from one workbook to another. My only issue is that empty cells are being added between data. Can anyone understand why? It looks like the script is skipping values which don't meet the condition of the if statement, but still copying a blank cell.
from openpyxl import load_workbook
from openpyxl import Workbook
wb = load_workbook('testData.xlsx')
wb2 = load_workbook('testTemplate.xlsx')
ws = wb.worksheets[0]
mr = ws.max_row
ws2 = wb2.worksheets[0]
mr2 = ws2.max_row
for row in ws.iter_rows(min_row = 1, min_col = 1, max_row = mr, max_col = 3):
for cell in row:
if cell.value == "A":
ws2.cell(row = mr2 + 1, column = 1).value = (cell.offset(column = + 1).value)
mr2 += 1
elif cell.value == "B":
ws2.cell(row = mr2 + 1, column = 2).value = (cell.offset(column = + 1).value)
mr2 += 1
elif cell.value == "C":
ws2.cell(row = mr2 + 1, column = 3).value = (cell.offset(column = + 1).value)
mr2 += 1
wb2.save('testTemplate.xlsx')
Your issue:
Giving Enter(mr2 += 1) every time after entering value as it return in if condition
Solution:
Create separate counter for different columns and Enter(Counter += 1) when value in entered in that column
As per example:
A = ws2.max_row
if cell.value == "A":
ws2.cell(row = A + 1, column = 1).value = (cell.offset(column = + 1).value)
A += 1
Full Code:
from openpyxl import load_workbook
from openpyxl import Workbook
wb = load_workbook('testData.xlsx')
wb2 = load_workbook('testTemplate.xlsx')
ws = wb.worksheets[0]
mr = ws.max_row
ws2 = wb2.worksheets[0]
A = ws2.max_row
B = ws2.max_row
C = ws2.max_row
for row in ws.iter_rows(min_row = 2, min_col = 1, max_row = mr, max_col = 2):
for cell in row:
if cell.value == "A":
ws2.cell(row = A + 1, column = 1).value = (cell.offset(column = + 1).value)
A += 1
elif cell.value == "B":
ws2.cell(row = B + 1, column = 2).value = (cell.offset(column = + 1).value)
B +=1
elif cell.value == "C":
ws2.cell(row = C + 1, column = 3).value = (cell.offset(column = + 1).value)
C +=1
wb2.save('testTemplate.xlsx')
I am trying to create a flask route that sends data to a function, that function creates an openpyxl excel file and returns the excel file to the route, and the route then returns the downloadable file to a React frontend. I'm not sure if this is the exact problem, but I am getting errors that the file is not found in my instance/files folder. Instead, the file is saving to my project's root directory. The same path is working for other routes, so I'm not sure what I'm doing wrong here/why it is saving elsewhere. I'm assuming this is why I can't return the excel file to the frontend, but it could be other issues with my function/route. Please help!
This is my openpyxl function:
def generate_prev_sim_csv(data):
get_dict = data
claims = data['claims']
setup_dict = data['setups']
summary_metric_headers = data['setupSummaryMetricHeaders']
filename = "Simulation_Summary.xlsx"
wb = Workbook()
sheet = wb.active
# styles
heading_font = Font(size=11, bold=True)
heading = NamedStyle(name='Heading')
wb.add_named_style(heading)
heading.font = heading_font
percent_value = NamedStyle(name='Percentage')
wb.add_named_style(percent_value)
percent_value.number_format = '0.00%'
# Claim Header
headers = ['Claim']
start_claim_header_row = 1
start_claim_header_col = 2
for i, header in enumerate(headers):
current_row = start_claim_header_row
column_letter = get_column_letter(start_claim_header_col)
cell_ref = f"{column_letter}{current_row}"
sheet[cell_ref] = header
sheet[cell_ref].style = heading
# Setup Header
setup_title = "Setup "
start_setup_header_row = 1
start_setup_header_col = 3
for header_index, header in enumerate(setup_dict):
current_row = start_setup_header_row
column_letter = get_column_letter(start_setup_header_col)
cell_ref = f"{column_letter}{current_row}"
sheet[cell_ref] = setup_title + str(header_index)
sheet[cell_ref].style = heading
for col_index, col_data in enumerate(setup_dict):
current_col = start_setup_header_col + 1
column_letter = get_column_letter(current_col)
cell_ref = f"{column_letter}{current_row}"
sheet[cell_ref] = setup_title + str(col_index + 1)
sheet[cell_ref].style = heading
# Side by Side Claim and Claim States Table
starting_col_index = 2
starting_row_index = 2
for index, claim in enumerate(claims):
current_row = starting_row_index + index
column_letter = get_column_letter(starting_col_index)
cell_ref = f"{column_letter}{current_row}"
sheet[cell_ref] = claim
sheet[cell_ref].style = heading
for i, setup in enumerate(setup_dict):
setup_claims_on = setup[3]
current_col = starting_col_index + i + 1
column_letter = get_column_letter(current_col)
cell_ref = f"{column_letter}{current_row}"
if claim in setup_claims_on:
sheet[cell_ref] = setup[2][claim]['Summary_Metrics']['Reach']
sheet[cell_ref].style = percent_value
elif setup[0][claim] == "Offered":
sheet[cell_ref] = "Already Offered"
elif setup[0][claim] == "Considered":
sheet[cell_ref] = "Considered"
elif setup[0][claim] == "Excluded":
sheet[cell_ref] = "Excluded"
else:
sheet[cell_ref] = ""
# Summary Metrics Header
start_metric_header_row = 16
start_metric_header_col = 2
for i, header in enumerate(summary_metric_headers):
current_row = start_metric_header_row
column_letter = get_column_letter(start_metric_header_col)
cell_ref = f"{column_letter}{current_row}"
sheet[cell_ref] = "Summary Metrics"
sheet[cell_ref].style = heading
# Summary Metrics Table
start_col_index = 2
start_row_index = 17
for i, header in enumerate(summary_metric_headers):
current_row = start_row_index + i
column_letter = get_column_letter(start_col_index)
cell_ref = f"{column_letter}{current_row}"
sheet[cell_ref] = header
sheet[cell_ref].style = heading
for id, setup in enumerate(setup_dict):
current_col = starting_col_index + id + 1
column_letter = get_column_letter(current_col)
cell_ref = f"{column_letter}{current_row}"
if header == "Subgroup":
sheet[cell_ref] = setup[5]
elif header == "Number of Respondents":
sheet[cell_ref] = setup[4]
elif header == "Average Liked":
sheet[cell_ref] = round(setup[1]["Average_Number_of_Items_Liked"], 2)
elif header == "Average Reach":
sheet[cell_ref] = setup[1]["Reach"]
sheet[cell_ref].style = percent_value
elif header == "Average Favorite":
sheet[cell_ref] = setup[1]["Favorite_Percentage"]
sheet[cell_ref].style = percent_value
else:
sheet[cell_ref] = ""
wb.save(filename=filename)
return filename
This is my route. I'm not sure what to do with the return from the function?:
#bp.route("/api/export_prev_sim_to_csv", methods=["GET", "POST"])
def export_simulations_to_csv():
data = request.get_json() or {}
print(data)
if not os.path.exists(current_app.instance_path):
os.mkdir(current_app.instance_path)
if not os.path.exists(os.path.join(current_app.instance_path, "files")):
os.mkdir(os.path.join(current_app.instance_path, "files"))
cs_fn = os.path.join(
current_app.instance_path, "files", "Simulation_Summary.xlsx"
)
openpyxl_file = generate_prev_sim_csv(data)
return send_file(
cs_fn,
mimetype=(
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
),
as_attachment=True,
cache_timeout=0,
)
You are saving the file in root directory in generate_prev_sim_csv function
filename = "Simulation_Summary.xlsx"
[...]
wb.save(filename=filename)
Wb.save creates a file if it doesn't exist so you don't need to create file in your route
Just change the filename to this in your openpyxl function
filename = 'instance/files/Simulation_Summary.xlsx'
I am trying to load an excel file using openpyxl library but I kept getting a value error. I also created a new excel file and tried loading the file using pandas but I still get an exception error related cell "C7".
openpyxl
DestFile ="C:\\Users\\yaxee\\OneDrive\\Desktop\\NBET Extraction data\\December Data Extration 2020 NBET\\XYX.xlsx"
wb2 = xl.load_workbook(DestFile)
Error
ValueError: invalid literal for int() with base 10: '7.0'
pandas
df = pd.read_excel (r'C:\Users\yaxee\OneDrive\Desktop\NBET Extraction data\December Data Extration 2020 NBET\XYX.xlsx')
Error
Exception: cell name 'C7.0' but row number is '7'
I can post the full error script if needed.
here is the full script i'm working with:
import openpyxl as xl
ExtractionFile ="C:\\Users\\yaxee\\OneDrive\\Desktop\\NBET Extraction data\\August Data Extration 2020 NBET\\NOR04082020.xlsx"
wb1 = xl.load_workbook(ExtractionFile, data_only=True)
daily_broadcast = wb1.worksheets[0]
DestFile ="C:\\Users\\yaxee\\OneDrive\\Desktop\\NBET Extraction data\\August Data Extration 2020 NBET\\SampleOct.xlsx"
wb2 = xl.load_workbook(DestFile)
peak_gen = wb2.worksheets[0]
off_gen = wb2.worksheets[1]
energy_gen = wb2.worksheets[2]
energy_sent = wb2.worksheets[3]
instlld_cap = wb2.worksheets[4]
gen_cap = wb2.worksheets[5]
onBar_cap = wb2.worksheets[6]
gen_6am = wb2.worksheets[7]
unutilized = wb2.worksheets[8]
col_count = 6
step = 2
read_start_row = 73
write_start_row = 4
amount_of_rows = 54
#peak generation capability code
for row in range(5, 34):
a = daily_broadcast.cell(row = row, column = 25)
peak_gen.cell(row = row-1,column = col_count).value = a.value
wb2.save(str(DestFile))
#off generation capability code
for row in range(5, 34):
b = daily_broadcast.cell(row = row, column = 27)
off_gen.cell(row = row-1,column = col_count).value = b.value
wb2.save(str(DestFile))
#Energy generated code
for row in range(39, 68):
c = daily_broadcast.cell(row = row, column = 25)
energy_gen.cell(row = row-35,column = col_count).value = c.value
wb2.save(str(DestFile))
#Energy dispatched code
for row in range(39, 68):
d = daily_broadcast.cell(row = row, column = 27)
energy_sent.cell(row = row-35,column = col_count).value = d.value
wb2.save(str(DestFile))
#Installed Capacity code
for i in range(0, amount_of_rows, step):
e = daily_broadcast.cell(row = read_start_row + i, column = 13)
instlld_cap.cell(row = write_start_row+(i/step),column = col_count).value = e.value
wb2.save(str(DestFile))
#Generation Capablity code
for i in range(0, amount_of_rows, step):
f = daily_broadcast.cell(row = read_start_row + i, column = 15)
gen_cap.cell(row = write_start_row+(i/step),column = col_count).value = f.value
wb2.save(str(DestFile))
#On Bar Capablity code
for i in range(0, amount_of_rows, step):
g = daily_broadcast.cell(row = read_start_row + i, column = 19)
onBar_cap.cell(row = write_start_row+(i/step),column = col_count).value = g.value
wb2.save(str(DestFile))
#Generation at 6am code
for i in range(0, amount_of_rows, step):
g = daily_broadcast.cell(row = read_start_row + i, column = 21)
gen_6am.cell(row = write_start_row+(i/step),column = col_count).value = g.value
wb2.save(str(DestFile))
[
This happens when a worksheet is created with the row or the column designation with a float point number. For example, worksheet.cell(row=1.0, column=1).value = 'some value'. While Excel reads the file without any issues, having openpyxl open the file causes the error. A simple remedy is to always use an integer for the row and the column designations.
The code I have wrote in Python for an infinite loop works fine the first time. However, it gives the following message upon the second run:
Traceback (most recent call last):
File "C:/Users/dell/PycharmProjects/pythonProject/main.py", line 27, in
symbol = str(symbol)
TypeError: 'tuple' object is not callable
Any ideas why I am not getting this message after second run?
from xlrd import open_workbook
import win32com.client as win32
from oandapyV20.contrib.requests import MarketOrderRequest
from oandapyV20.contrib.requests import TakeProfitDetails, StopLossDetails
import oandapyV20.endpoints.orders as orders
import oandapyV20
from oandapyV20 import API
import oandapyV20.endpoints.accounts as accounts
import oandapyV20.endpoints.pricing as pricing
import oandapyV20.endpoints.positions as positions
import easygui
import tkinter as tk
import time
while True:
time.sleep(5)
excel = win32.gencache.EnsureDispatch('Excel.Application')
for wb in excel.Workbooks:
if wb.Name == 'forex2.xlsx':
wb.Save()
wb = open_workbook('C:/Users/dell/Documents/forex2.xlsx')
xl_sheet = wb.sheet_by_index(0)
marginrate = xl_sheet.cell(1, 2)
symbol = xl_sheet.cell(1, 1)
symbol = str(symbol)
marginrate = str(marginrate)
symbol = symbol.replace("text:", "")
marginrate = 20
symbol = symbol.replace("'", "")
print("Symbol:", symbol)
print("Margin Rate:", marginrate)
access_token = "XXXX"
accountID = "XXXX"
client = API(access_token=access_token)
r = accounts.AccountDetails(accountID)
client.request(r)
dict = r.response
params = {"instruments": symbol}
r2 = pricing.PricingInfo(accountID=accountID, params=params)
rv2 = client.request(r2)
a = list(rv2.items())[1][1][0]
ask = float(a['closeoutAsk'])
print("Starting Ask:", ask)
a = list(dict.items())[0][1]
marginUsed = float(list(a.items())[25][1])
marginAvailable = float(list(a.items())[26][1])
balance = float(list(a.items())[9][1])
print("Margin Available:", marginAvailable)
print("Balance:", balance)
print("Margin Used + Margin Available:", balance)
STOP_LOSS = .001
TAKE_PROFIT = 100000
units0 = round((marginrate * marginAvailable) / ask * .95)
print("Order Units:", units0)
mktOrder = MarketOrderRequest(
instrument=symbol,
units=units0,
takeProfitOnFill=TakeProfitDetails(price=TAKE_PROFIT).data,
stopLossOnFill=StopLossDetails(price=STOP_LOSS).data)
r = orders.OrderCreate(accountID, data=mktOrder.data)
try:
rv = client.request(r)
except oandapyV20.exceptions.V20Error as err:
print("")
print("UNITS_INVALID")
else:
print("")
excel = win32.gencache.EnsureDispatch('Excel.Application')
for wb in excel.Workbooks:
if wb.Name == 'forex2.xlsx':
wb.Save()
book = open_workbook('C:/Users/dell/Documents/forex2.xlsx')
r = positions.PositionList(accountID=accountID)
client.request(r)
dict = r.response
a = list(dict.items())[0][1]
for i, element in enumerate(a):
long = a[i]
long2 = long['long']
symbol = long['instrument']
try:
averagePrice = long2['averagePrice']
except:
pass
else:
window = tk.Tk()
frame_a = tk.Frame()
label_a = tk.Label(master=frame_a, text="Hello")
label_a.pack()
frame_a.pack()
for sheet in book.sheets():
for rowidx in range(sheet.nrows):
row = sheet.row(rowidx)
for colidx, cell in enumerate(row):
if cell.value == symbol:
row = rowidx + 3
current_bid = sheet.cell(1, row)
current_bid = str(current_bid)
current_bid = float(current_bid.replace("number:", ""))
str = "Beginning Balance:", balance, "Current Bid:", current_bid, "Average Price:", averagePrice, "Current Profit:", round(
(current_bid - float(averagePrice)) * units0, 2)
print(str)
data = {"longUnits": "ALL"}
r = positions.PositionClose(accountID=accountID, instrument=symbol, data=data)
client.request(r)
The problem is your using
str = "Beginning Balance:", balance, "Current Bid:", current_bid, "Average Price:", averagePrice, "Current Profit:", round((current_bid - float(averagePrice)) * units0, 2) ,which replaces the function str with the variable you are assigning here. try replacing the name of this variable and it should work fine.
I am trying to copy the values from some cells but it give me this error, i tried even without using the def cell(x,y) but still the same error.
This is the error:
learn_tar.cell(row=learn_tar, column=1).value = sheet.cell(row=learn_tar, column=1).value
AttributeError: 'int' object has no attribute 'cell'
Source:
import openpyxl
def cell(x,y):
cell = sheet.cell(row=x,column=y).value
return cell;
def percentage(percent, whole):
return int((percent * whole) / 100.0);
ex = openpyxl.load_workbook("Final_excel2.xlsx")
sheet = ex.get_sheet_by_name('Sheet1')
num = [0,0,0]
per = [0,0,0]
for row in range(2,4798):
if cell(row,1) == '1: Progression':
num[0] = num[0] + 1
elif cell(row,1) == '2: Incidence':
num[1] = num[1] + 1
elif cell(row,1) == '3: Non-exposed control group':
num[2] = num[2] + 1
for column in range(2,49):
#doing stuff
per[0] = percentage(70,num[0])
per[1] = percentage(70,num[1])
per[2] = percentage(70,num[2])
learn_att = ex.create_sheet('Learn-Att',2)
learn_tar = ex.create_sheet('Learn-Tar',3)
test_att = ex.create_sheet('Test-Att',4)
test_tar = ex.create_sheet('Test-Tar',5)
learn_att = 1
learn_tar = 1
test_att = 1
test_tar = 1
for row in range(2,4798):
if row<=1391:
if row<=974:
learn_tar.cell(row=learn_tar, column=1).value = cell(row,1)
learn_att+= 1
learn_tar+= 1
else:
test_tar.cell(row = test_tar,column = 1).value = cell(row,1)
test_att+= 1
test_tar+= 1
for column in range(2,49):
if row<=1391:
if row<=974:
learn_att.cell(row = learn_att,column = column - 1).value = cell(row,column)
else:
test_att.cell(row = test_att,column = column - 1).value = cell(row,column)
You override learn_tar with 1:
learn_tar = ex.create_sheet('Learn-Tar',3)
...
learn_tar = 1
Remove:
learn_tar = 1
and:
learn_tar+= 1
from your code.