Add new rows to existing column of excel in python - python

I want to add new records every week to this existing file without creating a new one.
For example, Next I want to add record on date 6/13/2016
Randy->(13,23,13)
Shaw->(13,15,13)
and many such entries next two months. How do I do that? I am beginner so having trouble to put it in syntax.
I could do only this much
import xlrd
#Opening the excel file
file_location= "C:/Users/agodgh1a/Desktop/Apurva/EPSON.xlsx"
workbook= xlrd.open_workbook(file_location)
sheet=workbook.sheet_by_index(0)
Thank you!

The lib you're using looks like it only reads, not edits. Here's an example in openpyxl:
from openpyxl import Workbook, load_workbook
# create the file
wb = Workbook()
ws = wb.active
ws.append([1, 2, 3])
wb.save("sample.xlsx")
# re-open and append
wb = load_workbook("sample.xlsx")
ws = wb.active
ws.append([4, 5, 6])
wb.save("sample.xlsx")
Run that and you'll have a file sample.xlsx with both rows.

xlrd
is for reading operations only. Since you want perform a write operation use
xlwt
python module.
Refer to xlwt docs for the same

Related

How can i write on an XLS file using python?

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.

python - adding rows to an existing worksheet table

I'm working with the .xlsx file and it has a tab with a workhsheet table where lots of conditional formatting are used. From time to time I need to append this table with new rows.
My plan is to use python openpyxl (or other package) to append this table.
so far I could identify this table as
from openpyxl import load_workbook
wb=load_workbood(myfile)
ws=wb['mytab']
tab = wb.ws._tables[0]
Can I use something like .append() method or change data of this table to add more rows to it?
My goal is to keep the formatting.
I've already tried this approach -
Manipulate existing excel table using openpyxl and it doesn't' work for me
I'm using openpyxl 2.6.1
Regards,
Pavel
from openpyxl import load_workbook
filename= r'C:\Users\PC/test.xlsx'
wb = load_workbook(filename)
ws = wb['Hoja1']
ws["A1"] = "AAA"
ws["A2"] = "BBB"
wb.save(filename)
from openpyxl import load_workbook
wb=load_workbood(myfile)
ws=wb['mytab']
tab = ws.tables["Table1"]
tab.ref = f"A1:{ws.max_column}{ws.max_row}"

openpyxl: remove_sheet causes IndexError: list index out of range error on saving sheet

I am trying to use openpyxl to:
Open an Excel (2016) workbook which contains 3 worksheets (Sheet1,Sheet2,Sheet3)
Remove a worksheet (Sheet2)
Save the workbook to a different workbook minus Sheet2
from openpyxl import load_workbook
wb = load_workbook("c:/Users/me/book1.xlsx")
ws = wb.get_sheet_by_name('Sheet2')
wb.remove_sheet(ws)
wb.save("c:/Users/me/book2.xlsx")
The wb.save will generate an IndexError: list index out of range error and produce a corrupted book2.xlsx file which Excel cannot open.
I run into similar problem, only with xlwt library. Regardless, the cause is the same, You remove the sheet which is set as active sheet. So, to fix this, before saving workbook, set some other sheet as active. In openpyxl, it would be something like this:
from openpyxl import load_workbook
wb = load_workbook("c:/Users/me/book1.xlsx")
ws = wb.get_sheet_by_name('Sheet2')
wb.remove_sheet(ws)
wb._active_sheet_index = 0
wb.save("c:/Users/me/book2.xlsx")
I must mention that this is not very good programming practice, but there is no method to set active sheet, only to get one.
EDIT: Just found out that this repo was moved to bitbucket, and found that it has method for setting active sheet. Just use:
wb.active = 0

Write data into existing excel file and making summary table

I have to write some data into existing xls file.(i should say that im working on unix and couldnt use windows)
I prefer work with python and have tried some libraries like xlwt, openpyxl, xlutils.
Its not working, cause there is some filter in my xls file. After rewriting this file filter is dissapearing. But i still need this filter.
Could some one tell me about options that i have.
help, please!
Example:
from xlutils.copy import copy
from xlrd import open_workbook
from xlwt import easyxf
start_row=0
rb=open_workbook('file.xls')
r_sheet=rb.sheet_by_index(1)
wb=copy(rb)
w_sheet=wb.get_sheet(1)
for row_index in range(start_row, r_sheet.nrows):
row=r_sheet.row_values(row_index)
call_index=0
for c_el in row:
value=r_sheet.cell(row_index, call_index).value
w_sheet.write(row_index, call_index, value)
call_index+=1
wb.save('file.out.xls');
I also tried:
import xlrd
from openpyxl import Workbook
import unicodedata
rb=xlrd.open_workbook('file.xls')
sheet=rb.sheet_by_index(0)
wb=Workbook()
ws1=wb.create_sheet("Results", 0)
for rownum in range(sheet.nrows):
row=sheet.row_values(rownum)
arr=[]
for c_el in row:
arr.append(c_el)
ws1.append(arr)
ws2=wb.create_sheet("Common", 1)
sheet=rb.sheet_by_index(1)
for rownum in range(sheet.nrows):
row=sheet.row_values(rownum)
arr=[]
for c_el in row:
arr.append(c_el)
ws2.append(arr)
ws2.auto_filter.ref=["A1:A15", "B1:B15"]
#ws['A1']=42
#ws.append([1,2,3])
wb.save('sample.xls')
The problem is still exist. Ok, ill try to find machine running on windows, but i have to admit something else:
There is some rows like this:
enter image description here
Ive understood what i was doing wrong, but i still need help.
First of all, i have one sheet that contains some values
Second sheet contains summary table!!!
If i try to copy this worksheet it did wrong.
So, the question is : how could i make summary table from first sheet?
Suppose your existing excel file has two columns (date and number).
This is how you will append additional rows using openpyxl.
import openpyxl
import datetime
wb = openpyxl.load_workbook('existing_data_file.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
a = sheet.get_highest_row()
sheet.cell(row=a,column=0).value=datetime.date.today()
sheet.cell(row=a,column=1).value=30378
wb.save('existing_data_file.xlsx')
If you are on Windows, I would suggest you take a look at using the win32com.client approach. This allows you to interact with your spreadsheet using Excel itself. This will ensure that any existing filters, images, tables, macros etc should be preserved.
The following example opens an XLS file adds one entry and saves the whole workbook as a different XLS formatted file:
import win32com.client as win32
import os
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(r'input.xls')
ws = wb.Worksheets(1)
# Write a value at A1
ws.Range("A1").Value = "Hello World"
excel.DisplayAlerts = False # Allow file overwrite
wb.SaveAs(r'sample.xls', FileFormat=56)
excel.Application.Quit()
Note, make sure you add full paths to your input and output files.

copy a worksheet in openpyxl

I'm using openpyxl (unfortunately I don't know how to find out my version number, installed it about a month ago) on Windows with python 2.7 and want to copy a worksheet that I generated using a template.xlsx file to a new workbook. The template has a single worksheet that I alter. I want to load it n times and copy each version as a new worksheet to another workbook. Could also be the same workbook ifneedbe.
I found some hints here which took me here. The example doesn't work as it seems the add_sheet() method has been removed.
primary.add_sheet(copy.deepcopy(ws),ido+1)
AttributeError: 'Workbook' object has no attribute 'add_sheet'
Also couldn't find anything helpful in the API.
I'm afraid copying worksheets is not supported because it is far from easy to do.
I was struggling with it as you. But, I could find out the way to solve.
The best way I think to copy Excel worksheets using Openpyxl and Python:
from openpyxl import Workbook, load_workbook
# workbook source = wb1 and workbook destination = wb2
wb1 = load_workbook('file.xlsx')
wb2 = Workbook()
ws1 = wbs.active
ws2 = wbd.active
for r in plan1.iter_rows():
for c in r:
ws2[c.coordinate] = c.value
wb2.save('file2.xlsx')
The FOR loop with iter_rows() creates a named list with existing filled cells. And the 2nd FOR iterates in those cells ('A1','A2','B1' etc). The method .coordinate can be applied to the cell(c) and extract the Column,Row like 'A1' as a string. If we add it as an index of the worksheet, we can set it as a variable. Then just get the value of the cell(c), the magic is done.
We can do something with data during the loop and after save it to the file.

Categories