Python- Deleting a sheet in excel without it prompting you - python

How do you delete a sheet in excel without it prompting you? I am doing this with Dispatch in win32com.client.
import time, os.path, os
from win32com.client import Dispatch
path1 = 'C:\\example.xlsx'
path2 = 'C:\\Todolist2.xlsx'
xl = Dispatch("Excel.Application")
xl.Visible = True
wb1= xl.Workbooks.Open(Filename=path1)
wb2= xl.Workbooks.Open(Filename=path2)
ws1 = wb1.Worksheets(1)
ws2 = xl.ActiveSheet
ws1.Copy(Before=wb2.Worksheets(1))
ws2 = xl.ActiveSheet
ws2.Delete()

Related

How to save transformed file into new excel file using Openpyxl Python?

I have 3 excel files currently in my working directory. All 3 files has name that ends with "_Updated.xlsx". I wanted to transform the files such that all empty rows in each of the files get deleted. I have created function for it, but the only issue is I cannot save all transformed file using below code. Not sure what is wrong ? The reason for creating new file is I would like to save my raw files.
Python code
import openpyxl
import os
from openpyxl import load_workbook,Workbook
import glob
from pathlib import Path
Excel_file_path="/Excel"
for file in Path(Excel_file_path).glob('*_Updated.xlsx'):
wb=load_workbook(file)
wb_modified = False
for sheet in wb.worksheets:
max_row_in_sheet = sheet.max_row
max_col_in_sheet = sheet.max_column
sheet_modified = False
if max_row_in_sheet > 1:
first_nonempty_row = nonempty_row() # Function to find nonempty row
sheet_modified = del_rows_before(first_nonempty_row) #Function to delete nonempty row
wb_modified = wb_modified or sheet_modified
if wb_modified:
for workbook in workbooks:
for sheet in wb.worksheets:
new_wb = Workbook()
ws = new_wb.active
for row_data in sheet.iter_rows():
for row_cell in row_data:
ws[row_cell.coordinate].value = row_cell.value
new_wb.save("/Excel/"+sheet.title+"_Transformed.xlsx")
In case, if any one is still looking for answer to my above question. Below is the code that worked for me.
import openpyxl
import os
from openpyxl import load_workbook
import glob
from pathlib import Path
Excel_file_path="/Excel"
for file in Path(Excel_file_path).glob('*_Updated.xlsx'):
wb=load_workbook(file)
wb_modified = False
for sheet in wb.worksheets:
max_row_in_sheet = sheet.max_row
max_col_in_sheet = sheet.max_column
sheet_modified = False
if max_row_in_sheet > 1:
first_nonempty_row = get_first_nonempty_row() # Function to find nonempty row
sheet_modified = del_rows_before(first_nonempty_row) #Function to delete nonempty roW
file_name = os.path.basename(file)
wb.save("Excel/"+file_name[:-5]+"_Transformed.xlsx")
wb.close()

Python (OpenPyxl) openpyxl not write anything

Code :
wb = Workbook()
sdwbb = load_workbook(sdpath)
filename = os.path.basename(sdpath)
bulan = "September"
try:
sdp = sdwbb[bulan]
except:
sdwbb.create_sheet(bulan)
wb.save(filename)
time.sleep(0.5)
sdp = sdwbb[bulan]
cell_one = sdp['F1']
cell_one.value = 'test'
sdwbb.save(filename)
for your information I doesn't get any error but its doesn't write anything cell f1 sheet September
what I trying to do is to write on specific workbook ,sheet ,and cell
This is my code to write "test" in cel F1 (in the current sheet) in the file test.xlxs in the same folder:
from openpyxl import Workbook, load_workbook
wb = load_workbook("test.xlsx")
ws = wb.active
ws["F1"] = "test"
wb.save("test.xlsx")
print("done")
It's as easy as that :).
Also, you should devenitly check out the documentation of openpyxl: https://openpyxl.readthedocs.io/en/stable/tutorial.html#create-a-workbook

Python - Remove excel sheets using Filter()

I would like to only include certain sheets in an excel using the Filter() function.
This is my code so far:
import win32com.client as win32
from pathlib import Path
win32c = win32.constants
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open("C:/Prueba/GOOG.xlsm")
def included(sheet_name):
l = ['Report_Data', 'Report_Main']
if sheet_name in l:
return True
wb.__Sheets__ = filter(included, [sheet.Name for sheet in wb.Sheets]) # wb.__Sheets__ doesn't work of course...
My guess is that I need to properly access the Sheets attribute from workbook object and then the filter setup should do it. I tried "Sheets" for instance, but doesn't seem to work (also does not throw an error...).
Any ideas?
For the filter process you're using, you don't need to open the workbook. You can load the file using openpyxl and get the sheet names.
Try this code:
from pathlib import Path
import openpyxl
wb = openpyxl.load_workbook('C:/Prueba/GOOG.xlsm')
print("All Sheets:", wb.sheetnames)
def included(sheet_name):
l = ['Report_Data', 'Report_Main']
if sheet_name in l:
return True
wb.__Sheets__ = filter(included, wb.sheetnames) # wb.__Sheets__ doesn't work of course..
print(list(wb.__Sheets__))
If you prefer to stay with Win32 and have Excel actually open, you can use this code:
from win32com.client import Dispatch
import win32com
import win32com.client as win32
excel = win32com.client.dynamic.Dispatch('Excel.Application')
excel.Visible = True
wb = excel.Workbooks.Open("C:/Prueba/GOOG.xlsm")
print("All Sheets:",[wb.Sheets(i+1).Name for i in range(wb.Sheets.Count)])
def included(sheet_name):
l = ['Report_Data', 'Report_Main']
if sheet_name in l:
return True
ShtList = filter(included, [wb.Sheets(i+1).Name for i in range(wb.Sheets.Count)])
print(list(ShtList))
excel.Quit()
Here is the complete code to delete the extra sheets and save the workbook as a new file.
from win32com.client import Dispatch
import win32com
import win32com.client as win32
from shutil import copyfile
excel = win32com.client.dynamic.Dispatch('Excel.Application')
excel.Visible = True
filename = "C:/Prueba/GOOG.xlsm"
filenamenew = "C:/Prueba/GOOG.New.xlsm"
copyfile(filename, filenamenew)
wb = excel.Workbooks.Open(filenamenew)
print("All Sheets:",[wb.Sheets(i+1).Name for i in range(wb.Sheets.Count)])
def remove(sheet_name):
l = ['Report_Data', 'Report_Main']
if not sheet_name in l:
return True
ShtList = list(filter(remove, [wb.Sheets(i+1).Name for i in range(wb.Sheets.Count)]))
print("DelLst:",ShtList)
excel.DisplayAlerts = False # new prompt for delete
for s in ShtList:
print("del", s)
wb.Worksheets(s).Delete()
wb.Save()
excel.DisplayAlerts = True
excel.Quit()

Copy pasting multiple sheets into new workbook

The goal is to copy paste multiple existing sheets out of a workbook into a new workbook using xlwings. I have:
app = xw.App(visible=False)
book = xw.Book(path)
sheet_1 = book.sheets["Sheet1"]
sheet_2 = book.sheets["Sheet2"]
wb_res = xw.Book()
sheet_active = wb_res.sheets.active
sheet_1.api.Copy(Before=sheet_active)
This throws:
TypeError: Objects for SAFEARRAYS must be sequences (of sequences), or a buffer object.
Bonus question for the brave:
- How can I replace all formulas on a sheet for its value?
Thanks
If you can use win32com, you can try this:
from win32com.client import Dispatch
path1 = 'workbook1.xlsx'
path2 = 'workbook2.xlsx'
xl = Dispatch("Excel.Application")
wb1 = xl.Workbooks.Open(Filename=path1)
wb2 = xl.Workbooks.Open(Filename=path2)
ws1 = wb1.Worksheets(1)
ws1.Copy(Before=wb2.Worksheets(1))
wb2.Close(SaveChanges=True)
xl.Quit()

How, I can change Excel sheet tab background colour by python

I am generating report and want to highlight the tab when its fails.
import xlrd
import xlwt
wb = Workbook()
add_result = wb.add_sheet(req_id[req_num])
wb.save("report_name.xls")
xl = Dispatch( "Excel.Application")
xl.Visible = False
xlFile = "C:/tab_colour.xls"
wkb = xl.Workbooks.Open(xlFile)
sheet = xl.Worksheets.Item("SVP INFO")
sheet.Tab.Color = 255
wkb.Save()
wkb.Close()
xl.Quit()
xl = None

Categories