I have a .xlsx file in which multiple worksheets are there (with some content). I want to write some data into specific sheets say sheet1 and sheet5. Right now I am doing it using xlrd, xlwt, and xlutils copy() function. But is there any way to do it by opening the file in append mode and adding the data and save it (Like as we do it for the text/CSV files)?
Here is my code:
rb = open_workbook("C:\text.xlsx",formatting_info='True')
wb = copy(rb)
Sheet1 = wb.get_sheet(8)
Sheet2 = wb.get_sheet(7)
Sheet1.write(0,8,'Obtained_Value')
Sheet2.write(0,8,'Obtained_Value')
value1 = [1,2,3,4]
value2 = [5,6,7,8]
for i in range(len(value1)):
Sheet1.write(i+1,8,value1[i])
for j in range(len(value2)):
Sheet2.write(j+1,8,value2[j])
wb.save("C:\text.xlsx")
You can do it using the openpyxl module or using the xlwings module
Using openpyxl
from openpyxl import workbook #pip install openpyxl
from openpyxl import load_workbook
wb = load_workbook("C:\text.xlsx")
sheets = wb.sheetnames
Sheet1 = wb[sheets[8]]
Sheet2 = wb[sheets[7]]
#Then update as you want it
Sheet1 .cell(row = 2, column = 4).value = 5 #This will change the cell(2,4) to 4
wb.save("HERE PUT THE NEW EXCEL PATH")
the text.xlsx file will be used as a template, all the values from text.xlsx file together with the updated values will be saved in the new file
Using xlwings
import xlwings
wb = xlwings.Book("C:\text.xlsx")
Sheet1 = wb.sheets[8]
Sheet2 = wb.sheets[7]
#Then update as you want it
Sheet1.range(2, 4).value = 4 #This will change the cell(2,4) to 4
wb.save()
wb.close()
Here the file will be updated in the text.xlsx file but if you want to have a copy of the file you can use the code below
shutil.copy("C:\text.xlsx", "C:\newFile.xlsx") #copies text.xslx file to newFile.xslx
and use
wb = xlwings.Book("C:\newFile.xlsx") instead of wb = xlwings.Book("C:\text.xlsx")
As a user of both modules I prefer the second one over the first one.
For manipulating existing excel files you should use openpyxl. Other common libraries like the ones you are using dont support manipulating existing excel files. A workaround is to
save your output file as a different name - text_temp.xlsx
delete your original file - text.xlsx
rename your output file - text_temp.xlsx to text.xlsx
Related
I want to open a .xls file on python modify some rows and rewrite the new content on the same file because i use a macro to synchronise the data with SharePoint.
What libraries can i use?
You can do it using pandas with :
import pandas as pd
df = pd.read_excel('path/file.xls')
# modifications here ....
df.to_excel('path/file.xls')
Have you tried openpyxl?
It's very easy to modify xlsx file using this library.
from openpyxl import Workbook
wb = Workbook()
# grab the active worksheet
ws = wb.active
# Data can be assigned/updated directly to cells
ws['A1'] = 42
# Rows can also be appended
ws.append([1, 2, 3])
# Python types will automatically be converted
import datetime
ws['A2'] = datetime.datetime.now()
# Save the file
wb.save("sample.xlsx")
For more details you can refer to the openpyxl documentation.
I have a problem when I'm trying to save and than read excel file in python. So this is my function:
import openpyxl
import xlrd
from xlutils.copy import copy
import pandas as pd
def write_excel():
wb = openpyxl.load_workbook('8de69ccb60047ce5.xlsx')
sheet = wb.active
sheet['D18'] = 3
wb.save('8de69ccb60047ce5.xls')
df1 = pd.read_excel('8de69ccb60047ce5.xls', sheet_name='Лист1', header=None, skiprows=1, usecols="H,I")
print(df1)
workbook = xlrd.open_workbook('8de69ccb60047ce5.xls')
worksheet = workbook.sheet_by_index(0)
print(worksheet.cell(17, 8).value)
print(worksheet.cell(18, 8).value)
I'm changing cell D18, saving file and than trying to read other cells that has formulas but I get nothing (also cell without formulas read correctly).
But if I open file manually and save it in Excel that lines of code read those cells correctly.
The problem is this line wb.save('8de69ccb60047ce5.xls'). It saves changes in file but it doesn't saves file correctly (I don't know how to discribe it). How can I read cell with formula after changing the file in python?
Save a file as sample_book.xlsx with save function.
wb.save(filename = 'sample_book.xlsx')
For more info check out this link: https://www.soudegesu.com/en/post/python/create-excel-with-openpyxl/#save-file
I am using Python 3.7 and using OpenPyxl to read the sheet names from a large excel workbook (29MB) with 10 tabs.
import openpyxl
from openpyxl import load_workbook
wb = load_workbook(filename='h:\\Master_Portfoliio.xlsx')
print(wb.sheetnames)
The code above works for smaller files but when I use the same code for this file, the code just hangs. I would like to read the sheet names and then remove a tab and then copy a tab from another excel workbook into this workbook.
Have you tried the read_only = True flag?
wb = load_workbook(filename='h:\\Master_Portfoliio.xlsx', read_only = True)
I have an xlsm file and I have come across various methods to modify the file by creating a new file using openpyxl or xlw. Is there any way that I can modify my current file without having to create a new one everytime in the process?
from openpyxl import workbook
wb = openpyxl.load_workbook(filename = 'filename', read_only = False, keep_vba = True)
sheet = wb.get_sheet_by_name('UI')
wb.save('outfile.xlsm')
However, I do not want to create a new file each time I run the code and just want to modify my current file but openpyxl is not compatible with .xlsm type files?
Is there any way to do this?
OpenPyXL 2.6.2 does support xlsm files. Just overwrite your existing workbook.
import openpyxl
wb = openpyxl.load_workbook(filename = 'filename.xlsm', read_only = False, keep_vba = True)
sheet = wb['UI']
wb.save('filename.xlsm')
I would like to open .xlsx file using python for further manual process.
I tried
wb = load_workbook(filename = 'empty_book.xlsx')
by importing openpyxl module. But it does not open the file rather it just loads the file. Is there any other way to open excel file in python?
Thanks in advance
You could use pandas (also you need to install module xlrd)
import pandas as pd
excel_data = pd.read_excel('empty_book.xlsx')
Import openpyxl
>>> import openpyxl
Load the workbook that you are trying to read
>>> wb = openpyxl.load_workbook("Empty.xlsx")
Give the name of the sheet
>>> ws = wb['sheet_name']
For looping through values in the excel
for row in ws.rows:
for cell in row:
print cell.value
To edit the values
for row in ws.rows:
for cell in row:
cell.value = new_value