I'm trying to export a specific sheet from an excel file, but without a result. I want to export a specific sheet of paper to a completely new file What I have written is:
import openpyxl
book = openpyxl.load_workbook('C:\Python\test.xlsx')
a = (book.get_sheet_names())
sheet1 = book[a[5]]
sheet1.save('C:\Python\sheet2.xlsx')
Also, another thing I can't do,and look for a certain sheet if I have its name.
I apologize if the questions are simple, but it's been a few days since I started with python :)
Well, openpyxl does provide copy_worksheet() but it cannot be used between different workbooks. You can copy your sheet cell-by-cell or you can modify your starting workbook in memory and then you can save it with a different file name. Here is the code
import openpyxl
# your starting wb with 2 Sheets: Sheet1 and Sheet2
wb = openpyxl.load_workbook('test.xlsx')
sheets = wb.sheetnames # ['Sheet1', 'Sheet2']
for s in sheets:
if s != 'Sheet2':
sheet_name = wb.get_sheet_by_name(s)
wb.remove_sheet(sheet_name)
# your final wb with just Sheet1
wb.save('test_with_just_sheet2.xlsx')
Related
I am writing a script where I am accessing a worksheet from a Workbook using openpyxl using the code:
wb = load_workbook('Excel.xlsm',read_only=False ,keep_vba=True)
ws = wb.active
Now after updating some of the values in the Excel file I am plotting a graph by reading some portion of the Excel file in Pandas data frame using the code:
hsif=pd.read_excel("Excel.xlsm",sheet_name="K0 Reg Patch Util",skiprows=34)
Now as you can see for reading the Excel sheet in Pandas data frame I am using the sheet name. The problem is I want to give the sheet name as the name of Active sheet in the Workbook. Can somebody please tell me how to get the name of the active sheet or at least sheet no of an active sheet in the Workbook?
I am able to get a reference to active sheet using openpyxl as:
ws = wb.active
But this gives the reference to active sheet not the name of the sheet. I require the name for reading the sheet in pandas data frame or at least the sheet no of the active sheet.
Can somebody tell me how to do that using Pandas or Openpyxl?? Or at least point a way of how to read the active sheet using Pandas?
The Worksheet object in openpyxl has a .title property - hence, you can simply do:
ws_name = wb.active.title
Here is a sample code where i am trying to print the number of rows in the excel file each time a new row is inserted.The code does not work ,because i believe it's not interacting with the excel file at run time.
import xlrd
loc = r'C:\Users\dell\Desktop\sample2.xlsx'
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
k = sheet.nrows
while(True):
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
k1 = sheet.nrows
if(k1 > k):
print(k1)
k=k1
I think you misunderstand how the library xlrd works. It provides you with an interface to Excel files, not to an Excel session of an Excel instance somebody is working on in parallel. Everything you do in Excel is not written to the according file until you save the workbook. Hence, this is the moment when your code reads updated cells, not already when cells are changed.
I am using xlwings to place stock data I pull from the internet into worksheets. The workbook opens with a Sheet1, and upon running my program creates various sheets named according to the stock index. This leaves Sheet1 and causes problems with other methods I want to call. I want to test for any sheets that contain Sheet (plus an integer) and subsequently delete it similar to how you would test for the presence of a list element using the in operator. How would I go about doing this in xlwings? Current xlwings methods only allow sheets in which you manually name to be deleted.
My attempts have been rather lackluster. I've been trying loops to recognize the sheet names but to no avail. Here is my attempt to do so.
import xlwings as xw
wb = xw.Book('practice.xlsx')
for sheet in wb.sheets:
if 'Sheet' in sheet:
xw.Sheet[sheet].delete()
This works:
import xlwings as xw
wb = xw.Book('practice.xlsx')
for sheet in wb.sheets:
if 'Sheet' in sheet.name:
sheet.delete()
is the syntax more like sheet.api.Delete()? My xlwings is broken right now to check the exact syntax.
You can check, if the given sheet exist and you can delete the existing sheet and add a new one.
import xlwings as xw
def df_to_excel_util(excel,sheet_to_dataFrame_map):
with xw.App(visible=False) as app:
wb = app.books.open(excel)
current_sheets = [sheet.name for sheet in wb.sheets]
for sheet_name in sheet_to_dataFrame_map.keys():
if sheet_name in current_sheets:
wb.sheets[sheet_name].delete()
new_sheet = wb.sheets.add(after=wb.sheets.count)
new_sheet.range('A1').value = sheet_to_dataFrame_map.get(sheet_name)
new_sheet.name = sheet_name
wb.save()
if you have sheet object, you can delete as given below
sheet.delete()
if you want to delete a sheet with a given name.
wb.sheets['sheet_name'].delete
Every week I generate a large excel sheet using Python/Pandas. However, the xls writer in Pandas does not allow one to format the excel sheets likely because of the proprietary format. Currently, I have to go worksheet by worksheet in the newly generated file and copy the formatting from the sheet the week before which is a little obnoxious.
Is there a way (in order of preference):
Copy all the formatting from one excel sheet to another in Python
Format Paint all sheets from a workbook to a second workbook
This would be making a sheet with formatting and links which I could update and than resave, but I'm hoping for a solution like (1) or (2).
I'd do it that way:
import win32com.client
xlPasteFormats = -4122
xlPasteSpecialOperationNone = -4142
excelInstance = win32com.client.gencache.EnsureDispatch ("Excel.Application")
workbook = excelInstance.Workbooks.Item(1)
worksheet = workbook.Worksheets(1)
worksheet2 = workbook.Worksheets(3)
cells1 = worksheet.UsedRange
cells2 = worksheet2.UsedRange
cells1.Copy()
cells2.PasteSpecial(xlPasteFormats, xlPasteSpecialOperationNone)
which is quite similar to solution in VBA, because uses the same functions, but does it via COM, so you stay completely in Python.
In this code I had workbook open. If you want to open workbook you should put:
filepath = r"path:\To\Excel\Workbook"
excelInstance.Workbooks.Open(filepath)
Here is the VBA way to do it (from sancho.s's answer in this question), assuming the sheets in each workbook are named the same. You may be able to use those objects in Python, or at least create this macro in the workbook you copy from.
Sub FormatMAC()
Dim wb1 As Workbook, wb2 As Workbook
Set wb1 = Workbooks("Results_2012 - Template - Master.xlsx")
Set wb2 = Workbooks("Copy of Results_2012 - Template1.xlsm")
Dim ws1 As Worksheet, ws2 As Worksheet
For Each ws1 In wb1.Worksheets
Set ws2 = wb2.Worksheets(ws1.Name)
ws1.Cells.Copy
ws2.Cells.PasteSpecial (xlPasteFormats)
Next ws1
End Sub
I have created an excel sheet using XLWT plugin using Python. Now, I need to re-open the excel sheet and append new sheets / columns to the existing excel sheet. Is it possible by Python to do this?
After investigation today, (2014-2-18) I cannot see a way to read in a XLS file using xlwt. You can only write from fresh. I think it is better to use openpyxl. Here is a simple example:
from openpyxl import Workbook, load_workbook
wb = Workbook()
ws = wb.create_sheet()
ws.title = 'Pi'
ws.cell('F5').value = 3.14156265
wb.save(filename=r'C:\book2.xls')
# Re-opening the file:
wb_re_read = load_workbook(filename=r'C:\book2.xls')
sheet = wb_re_read.get_sheet_by_name('Pi')
print sheet.cell('F5').value
See other examples here: http://pythonhosted.org/openpyxl/usage.html (where this modified example is taken from)
You read in the file using xlrd, and then 'copy' it to an xlwt Workbook using xlutils.copy.copy().
Note that you'll need to install both xlrd and xlutils libraries.
Note also that not everything gets copied over. Things like images and print settings are not copied, for example, and have to be reset.