Blessings,
I am trying to convert my current dataframe into a worksheet so i'll be able to save properly.
For some reason while trying to save to xlsx after editing a df using df.to_excel it overwrites to the top left row instead of editing the cells I originally changed.
ws.save() does seem to work fine though.
What I am using to write :
from datetime import date
import pandas as pd
import argparse
import logging
import sys
import os
# Create logger
logging.basicConfig(level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler(filename="info.log"),
logging.StreamHandler(sys.stdout)
])
logger = logging.getLogger()
def inventory():
"""This will allow interaction within Inventory.xlsx."""
today = date.today()
computer_date = today.strftime("%m-%d-%Y")
file = "MMEX Inventory.xlsx"
df = pd.ExcelFile(file).sheet_names
# Filter sheets
counter = 0
sheets = []
for sheet in df:
if sheet == "EXTRA" or sheet == "Inventory Rules" or sheet == "Removed lines" or sheet == "EOL_Hynix_SODIMM" \
or sheet == "EV" or sheet == "LPDDR4" or sheet == "LP4":
pass
else:
counter += 1
sheets.append(sheet)
# Added arguments to take
parser = argparse.ArgumentParser(description="Will allow interaction within Inventory")
parser.add_argument("num", help="What memory are you looking for? min of 2 letters are "
"sufficient.")
parser.add_argument("-m", "--subtract", type=int, metavar='', help="Will add to mmex and subtract from cabinet")
parser.add_argument("-c", "--add", type=int, metavar='', help="Will add to cabinet and subtract from mmex")
args = parser.parse_args()
# Loop through sheets
counter = 0
for i in sheets:
if counter == len(sheets) + 1:
break
else:
# Read xlsx and current sheet
df = pd.read_excel(f"{file}", f"{sheets[counter]}")
# Compare and keep matching columns
a = df.columns
b = ['IDC S/N', 'ECC', 'Cabinet Qty', 'MMEX', 'VDR']
keep_columns = [x for x in a if x in b]
# Maximum width on output
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', None)
# Search within IDC S/N for argument
df = df.loc[df['IDC S/N'].str.lower().str.contains(args.num.lower(), na=False), keep_columns]
df.reset_index(drop=True, inplace=True)
# Enable user to edit 'Cabinet Qty' or 'MMEX'
if args.add:
if df.empty:
pass
else:
# Check whether calculation approves
check = df.loc[df["IDC S/N"].str.lower().str.contains(args.num.lower(),
na=False), 'MMEX']
for num in check:
if num - args.add < 0:
print(f"\n\n{df}")
logger.info(f"\n\n\nYou cannot do that.\n"
f"While available quantity on MMEX is {num}\n"
f"You are trying to subtract it by {args.add}\n")
exit()
else:
pass
# Log user and changes
logger.info(f"\n\nBeing edited by - {os.getlogin()}")
logger.info(f"The following changes are being made in sheet - {sheets[counter]}\n{df}")
# Make changes to 'Cabinet Qty/MMEX'
df.loc[df['IDC S/N'].str.lower().str.contains(args.num.lower(),
na=False), 'Cabinet Qty'] += args.add
df.loc[df['IDC S/N'].str.lower().str.contains(args.num.lower(),
na=False), 'MMEX'] -= args.add
# Save changes
with pd.ExcelWriter(file,
engine="openpyxl", mode="a", if_sheet_exists="overlay") as writer:
df.to_excel(writer, sheet_name=f"{sheets[counter]}")
logger.info(f"The following changes have been made \n{df}")
elif args.subtract:
if df.empty:
pass
else:
# Check whether calculation approves
check = df.loc[df["IDC S/N"].str.lower().str.contains(args.num.lower(),
na=False), 'Cabinet Qty']
for num in check:
if num - args.subtract < 0:
print(f"\n\n{df}")
logger.info(f"\n\n\nYou cannot do that.\n"
f"While available quantity on 'Cabinet Qty' is {num}\n"
f"You are trying to subtract it by {args.subtract}\n\n")
exit()
else:
pass
# Log user and changes
logger.info(f"\n\nBeing edited by - {os.getlogin()}")
logger.info(f"The following changes are being made in sheet - {sheets[counter]}\n{df}")
# Make Changes to 'Cabinet Qty/MMEX'
df.loc[df["IDC S/N"].str.lower().str.contains(args.num.lower(),
na=False), 'Cabinet Qty'] -= args.subtract
df.loc[df['IDC S/N'].str.lower().str.contains(args.num.lower(),
na=False), 'MMEX'] += args.subtract
# Save changes
with pd.ExcelWriter(file,
engine="openpyxl", mode="a", if_sheet_exists="overlay") as writer:
df.to_excel(writer, sheet_name=f"{sheets[counter]}")
logger.info(f"The following changes have been made \n{df}")
else:
# Convert from float to int
try:
df['MMEX'] = df['MMEX'].astype(int)
df['VDR'] = df['VDR'].astype(int)
except KeyError:
pass
finally:
pass
# Will prevent empty dataframes when looping from sheets
if df.empty:
counter += 1
else:
print(f"\n{sheets[counter]}\n" f"{df}\n")
counter += 1
if __name__ == "__main__":
inventory()
Its output :
It basically overwrites to the top left instead of appending the current df.
While wb.save() does this instead:
Edit :
To summarize it all very shortly, I need to convert this df command df = df.loc[df['IDC S/N'].str.lower().str.contains(args.num.lower(), na=False), keep_columns]
Look within 'IDC S/N' for anything that contains args.num.lower as input and filter using only certain columns (keep_columns)
This needs to be converted into a ws commands (openpyxl), if anyone knows how to do this ill be more than happy :)
OpenPyXL documentation has a section related to working with pandas.
In your case, you'll need the openpyxl.utils.dataframe.dataframe_to_rows function.
From the documentation:
from openpyxl.utils.dataframe import dataframe_to_rows
wb = Workbook()
ws = wb.active
for r in dataframe_to_rows(df, index=True, header=True):
ws.append(r)
What I used was
# Will allow conversion to letters in later use
characters = 'abcdefghijklmnopqrstuvwxyz'
# Look for IDC S/N column
counter = 0
for col in df.columns:
if col == 'IDC S/N':
print(col)
print(counter)
break
else:
counter += 1
# Find 'IDC S/N' within xlsx
if ws[f"{characters[counter]}1"].value == "IDC S/N":
print('IDC S/N Exists.')
else:
print('IDC S/N Missing, Will stop')
quit()
# Converted numbers to letters - 1 = A , 2 = B
header = characters[counter]
# Search for memory within 'IDC S/N'
counter = 0
print(header)
for cell in ws[header]:
print(cell)
From here I can edit cells because I have both header and index ..
If anyone has a more efficient alternative please do share!
Related
I have a csv file that is generated that has some information in the first line. I'm trying to skip it but it doesn't seem to work. I tried looking at several suggestions and examples.
I tried using skiprows.
I also looked at several other examples.
Pandas drop first columns after csv read
https://datascientyst.com/pandas-read-csv-file-read_csv-skiprows/
Nothing I tried worked the way I wanted it.
When I got it to work it deleted the entire row.
Here is a sample of the code
# Imports the Pandas Module. It must be installed to run this script.
import pandas as pd
# Gets source file link
source_file = 'Csvfile.csv'
# Gets csv file and encodes it into a format that is compatible.
dataframe = pd.read_csv(source_copy, encoding='latin1')
df = pd.DataFrame({'User': dataframe.User, 'Pages': dataframe.Pages, 'Copies': dataframe.Copies,
'Color': dataframe.Grayscale, 'Duplex': dataframe.Duplex, 'Printer': dataframe.Printer})
# Formats data so that it can be used to count Duplex and Color pages.
df.loc[df["Duplex"] == "DUPLEX", "Duplex"] = dataframe.Pages
df.loc[df["Duplex"] == "NOT DUPLEX", "Duplex"] = 0
df.loc[df["Color"] == "NOT GRAYSCALE", "Color"] = dataframe.Pages
df.loc[df["Color"] == "GRAYSCALE", "Color"] = 0
df.sort_values(by=['User', 'Pages'])
file = df.to_csv('PrinterLogData.csv', index=False)
# Opens parsed CSV file.
output_source = "PrinterLogData.csv"
dataframe = pd.read_csv(output_source, encoding='latin1')
# Creates new DataFrame.
df = pd.DataFrame({'User': dataframe.User, 'Pages': dataframe.Pages, 'Copies': dataframe.Copies,
'Color': dataframe.Color, 'Duplex': dataframe.Duplex, 'Printer':
dataframe.Printer})
# Groups data by Users and Printer Sums
Report1 = df.groupby(['User'], as_index=False).sum().sort_values('Pages', ascending=False)
Report2 = (df.groupby(['Printer'], as_index=False).sum()).sort_values('Pages', ascending=False)
Sample Data
Sample Output of what I'm looking for.
This is an early draft of what you appear to want for your program (based on the simulated print-log.csv):
import csv
import itertools
import operator
import pathlib
CSV_FILE = pathlib.Path('print-log.csv')
EXTRA_COLUMNS = ['Pages', 'Grayscale', 'Color', 'Not Duplex', 'Duplex']
def main():
with CSV_FILE.open('rt', newline='') as file:
iterator = iter(file)
next(iterator) # skip first line if needed
reader = csv.DictReader(iterator)
table = list(reader)
create_report(table, 'Printer')
create_report(table, 'User')
def create_report(table, column_name):
key = operator.itemgetter(column_name)
table.sort(key=key)
field_names = [column_name] + EXTRA_COLUMNS
with pathlib.Path(f'{column_name} Report').with_suffix('.csv').open(
'wt', newline=''
) as file:
writer = csv.DictWriter(file, field_names)
writer.writeheader()
report = []
for key, group in itertools.groupby(table, key):
report.append({column_name: key} | analyze_group(group))
report.sort(key=operator.itemgetter('Pages'), reverse=True)
writer.writerows(report)
def analyze_group(group):
summary = dict.fromkeys(EXTRA_COLUMNS, 0)
for row in group:
pages = int(row['Pages']) * int(row['Copies'])
summary['Pages'] += pages
summary['Grayscale'] += pages if row['Grayscale'] == 'GRAYSCALE' else 0
summary['Color'] += pages if row['Grayscale'] == 'NOT GRAYSCALE' else 0
summary['Not Duplex'] += pages if row['Duplex'] == 'NOT DUPLEX' else 0
summary['Duplex'] += pages if row['Duplex'] == 'DUPLEX' else 0
return summary
if __name__ == '__main__':
main()
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])
I have a spreadsheet. It has Identifying numbers and then multiple codes associated to those numbers.
For example;
ID
Code
1
ABC1234
1
CBA1234
2
ABS1234
2
DEF3456
etc...
I am trying to iterate through the informatoion and create dictionaries with ID as the Key and a list of Codes as the value. My prblem is that the values are all being split into the individual characters. i.e;
{1: ['A', 'B', 'C', '1', '2', '3', '4', 'C', 'B', 'A', '1', '2', '3', '4']}
The code I have is
from openpyxl import *
FilePath = "File.xlsx"
wb = load_workbook(filename=FilePath)
Sheet = wb.active
Sheet1 = wb['Sheet1']
Sheet2 = wb['Sheet2']
Dict1 = {}
UnitPlace = Sheet1.iter_cols(min_row=2, max_row=2, min_col=18, max_col=110)
Dict = {}
def add_values_in_dict(sample_dict, key, list_of_values):
if key not in sample_dict:
sample_dict[key] = list()
sample_dict[key].extend(list_of_values)
return sample_dict
def read():
for SID2 in Sheet2['A']:
UnitInSheet2 = Sheet2['D'+(str(SID2.row))].value
Dict1 = add_values_in_dict(Dict, SID2.value, UnitInSheet2)
print (Dict1)
for SID1 in Sheet1['D']:
Rows = SID1.row
read()
Update: Reading Excel file using Openpyxl
We can iterate the rows using Openpyxl. Then we store the ID-codes as a dictionary where ID is the key and Code is the list of values.
from openpyxl import load_workbook
def read_file_openpyxl(file_path):
wb = load_workbook(filename=file_path)
sheet_1 = wb['Sheet1']
frequency = {}
for row in sheet_1.values:
if type(row[0]) == int:
id = row[0]
code = row[1]
if id in frequency:
frequency[id].append(code)
else:
frequency[id] = [code]
return frequency
if __name__ == "__main__":
FilePath = "dummy.xlsx"
print(read_file_openpyxl(FilePath))
Output:
{1: ['ABC1234', 'CBA1234'], 2: ['ABS1234', 'DEF3456']}
Alternative solution using Pandas:
Alternatively, you can use pandas.read_excel method to read the excel file.
import pandas as pd
def read_data(file_path):
dataset = pd.read_excel(file_path)
ids = list(dataset["ID"])
codes = list(dataset["Code"])
frequency = {}
for i in range(len(ids)):
id = ids[i]
code = codes[i]
if id in frequency:
frequency[id].append(code)
else:
frequency[id] = [code]
return frequency
if __name__ == "__main__":
FilePath = "dummy.xlsx"
freq = read_data(FilePath)
print(freq)
Output:
{1: ['ABC1234', 'CBA1234'], 2: ['ABS1234', 'DEF3456']}
Explanation:
First, we read the excel file using pandas.read_excel method.
Then we separated ids and codes with the rows of the excel sheet.
We used a dictionary named frequency to store the occurrences of code for each unique id.
References:
Documentation on Openpyxl
Documentation on pandas.read_excel method
I favor list comprehension more, following is my solution
# Import openpyxl
# Note: openpyxl package provides both read and write capabilities to excel
import openpyxl
import os
# Class definitions should use CamelCase convention based on pep-8 guidelines
class CustomOpenpyxl:
# Initialize the class with filename as only argument
def __init__(self, _my_file_name):
assert _my_file_name.split('.')[-1] == 'xlsx', 'Input file is not xlsx'
self.my_filename = _my_file_name
self.my_base_wb = openpyxl.load_workbook(self.my_filename, read_only=False)
# following line will get the names of worksheets in the workbook
self.ws_names_in_my_base_wb = self.my_base_wb.sheetnames
# following line will set the last worksheet in the workbook as active
self.my_base_active_ws = self.my_base_wb.active
# Method to set a specific worksheet as active where column names are in row#1
# Argument to this method is: - worksheet name
def active_ws(self, _ws_name):
# if the worksheet name exists in the workbook
if self.if_ws_in_wb(_ws_name):
self.my_base_active_ws = self.my_base_wb[_ws_name]
else:
print('Worksheet {} not found in workbook'.format(_ws_name))
# Method to check if a given worksheet exists in workbook
# Argument to this method is: workbook name
def if_ws_in_wb(self, _ws_name):
# if worksheet exists in list of worksheets of workbook returns True else False
if _ws_name in self.ws_names_in_my_base_wb:
return True
return False
# Create a dictionary from excel cell values
# No arguments to this method
def create_dict_from_values(self):
# Create an empty dictionary
_my_dict = dict()
# get the unique keys (numeric) from the first column of the worksheet
_my_keys = set([_row[0] for _row in self.my_base_active_ws.values if str(_row[0]).isdigit()])
# Iterate over the keys and add the values as a list
for _ in _my_keys:
# using list comprehension add the values to the key or keys
_my_dict[_] = [_row[1] for _row in self.my_base_active_ws.values if _row[0] == _]
return _my_dict
_my_file_path = os.getcwd()
_my_file_name = 'Book1.xlsx'
# Instantiate an object using the newly created class in this code block
# So that this object gets access to all methods in the class
_my_src_obj = CustomOpenpyxl(_my_file_name)
print(_my_src_obj.create_dict_from_values())
####################################################################PRINT Result################################################################################
{1: ['ABC1234', 'CBA1234'], 2: ['ABS1234', 'DEF3456']}
Process finished with exit code 0
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))
Given below is my code:
from os.path import join
from xlutils.copy import copy
from xlrd import open_workbook,cellname
from os.path import join, dirname, abspath
import xlwt
def Trend():
fname = join(dirname(dirname(abspath(__file__))),'Data Files', 'Processed Data', 'TrendAnalysis.xls')
# Open the workbook
book = open_workbook(fname, formatting_info=True)
wb = copy(book) # a writable copy (I can't read values out of this, only write to it)
total=0.
style = xlwt.easyxf('font: bold 1, name Calibri')
style1 = xlwt.easyxf('font: name Calibri')
for i in range(2,25):
if(i==1):
pass
else:
sheet = book.sheet_by_index(i)
w_sheet = wb.get_sheet(i) # the sheet to write to within the writable copy
cols = sheet.ncols # Number of columns
rows = sheet.nrows # Number of rows
for column in range(1,cols):
for row in range(1,rows):
if(sheet.cell(row,column).value == '-'):
pass
else:
total=total+sheet.cell(row,column).value
w_sheet.write(row+1, column, total, style1)
total=0
w_sheet.write(row+1,0, 'TOTAL', style)
i=i+1
s=book.sheet_by_index(0)
w = wb.get_sheet(0)
cols = s.ncols # Number of columns
rows = s.nrows # Number of rows
for row in range(1,rows):
if(s.cell(row,0).value== "ISU-GOV Domestic"):
for column in range(0,3):
a=s.cell(row,column).value
b=s.cell(21,column).value
w.write(21,column,a)
w.write(row,column,b)
elif(s.cell(row,0).value== "ISU-GOV Overseas"):
for column in range(0,3):
a=s.cell(row,column).value
b=s.cell(23,column).value
w.write(row,column,b)
w.write(23,column,a)
elif(s.cell(row,0).value== "ISU-MFG (TML)"):
for column in range(0,3):
a=s.cell(row,column).value
w.write(24,column,a)
b=s.cell(20,column).value
w.write(12,column,b)
elif(s.cell(row,0).value== "NGM-INDIA"):
for column in range(0,3):
a=s.cell(row,column).value
w.write(25,column,a)
else:
c=s.cell(row,0).value
w.write(row, 0, c)
for column in range(1,cols):
for row in range(1,20):
if(s.cell(row,column).value == '-'):
pass
else:
total=total+s.cell(row,column).value
w.write(20, column, total, style1)
total=0
w.write(20,0, 'SUB TOTAL', style)
for column in range(1,cols):
for row in range(20,rows):
if(s.cell(row,column).value == '-'):
pass
else:
total=total+s.cell(row,column).value
w.write(26, column, total, style1)
total=0
w.write(26,0, 'SUB TOTAL', style)
for column in range(1,cols):
for row in range(1,rows):
if(s.cell(row,column).value == '-'):
pass
else:
total=total+s.cell(row,column).value
w.write(27, column, total, style1)
total=0
w.write(27,0, 'GRAND TOTAL', style)
wb.save('fname')
The changes made to the excel file do not get reflected. The compilation doesnt give an errors ,yet none of these changes have been made on that excel sheet. Could you please help me sort the issue .?
The line in your program that says:
wb.save('fname')
will save to a file named 'fname'.
You want to use your fname variable, rather than the literal string 'fname', so that line should read:
wb.save(fname)