How to add new column and row to .xls file using xlrd - python

How do you add a new column and/or row to a sheet in xlrd?
I have a .xls file that I read using open_workbook() and I need to add a new column("bouncebacks") to the first sheet then new rows to that sheet but I cannot find any functions in the xlrd documentation that shows how to add new rows and/or columns?
If I cant add a row/column in xlrd is there another way/library that allows me to add a row or column to an .xls file?
Can you show me how I can add a row and column to a sheet?
import xlrd
book = xlrd.open_workbook("abc.xls")
sheet = book.sheet_by_index(0)
# how do I add a new column("bouncebacks") to the sheet?
# how do I add a new row to the sheet?

xlrd reads xls files. xlwt creates new xls files. You need xlutils. Read this. Work through the tutorial that you'll find mentioned there.

xlrd is for reading from an .xls file. for writting to it use xlwt.

Related

Is it possible to append data to an xls file in Python?

I am trying to add a large dataset to an existing xls spreadsheet.
I'm currently writing to it using a pandas dataframe and the .to_excel() function, however this erases the existing data in the (multi-sheet) workbook. The existing spreadsheet is very large and complex,it also interacts with several other files, so I can't convert it to xlsx or read and rewrite all of the data, as I've seen some suggestions on other questions. I want the data that I am adding to be pasted starting from a set row in an existing sheet.
Yes , you can use the library xlsxwriter , link= https://xlsxwriter.readthedocs.io
code example :
import xlsxwriter
Name="MyFile"+".xlsx"
workbook = xlsxwriter.Workbook(Name)
worksheet = workbook.add_worksheet()
worksheet.write("A1", "Incident category".decode("utf-8"))
worksheet.write("B1", "Longitude".decode("utf-8"))
worksheet.write("C1", "Latitude".decode("utf-8"))
workbook.close()

How to copy and paste multiple sheet for column's data with the same column name to another excel file

I have two different Excel files One is the master I need to update and the second one contains the data I need to copy and paste So....
This is my master excel file I want to update looks like this
Excel Master
and this excel which contains column data I need to copy it to the master file, as thee's are three sheets called GSM_CDDData, UMTS_CDDData, and LTE_CDDData and the three sheets contains the same column name which I need to copy it's data and add them to the Master Excel, as the columns name is CELLNAME
and this excel looks like
Source
After Copying this data ,I want to paste them in the Master Excel in column called CELL
So any Ideas how to do that?.....
as I know the supported library pandas and openpyxl
If you want to copy and paste the data itself, you might consider use of the pywin32 package (if you have Windows)
from win32com.client import Dispatch
xl = Dispatch("Excel.Application")
wb1 = xl.Workbooks.Open(Filename=file_name)
ws1 = wb1.Worksheets(sheet_1)
ws2 = wb1.Worksheets(sheet_2)
ws1.Columns(index_number).Copy(ws2.Columns(index_number))
If you don't want to use pywin32, you might just import the various columns using
pd.read_excel()
and append or concatenate the objects. From there you can save the new dataframe using to_excel.

Using pandas to replace data in excel sheet

I tried to come up with a way to copy data from a sheet in an excel file as
import pandas as pd
origionalFile = pd.ExcelFile('AnnualReport-V5.0.xlsx')
Transfers = pd.read_excel(origionalFile, 'Sheet1')
I have another excel file, which named 'AnnualReport-V6.0.xlsx', it has existing data in the sheet named 'Transfers', I tried to use the dataframe I created easily on to replace data in the sheet 'Transfers' in 'AnnualReport-V6.0.xlsx' from column B, leave column A as it is.
I did a few searches, the closest to what I want is this
Modifying an excel sheet in a excel book with pandas
but it does not allow me the keep column A in the original sheet (column A has some equations I do want to keep them), any idea how to do it? Thanks
Would reading column A and inserting it to the fresh data you want to write solve your problem?

xlsxwriter: is there a way to open an existing worksheet in my workbook?

I'm able to open my pre-existing workbook, but I don't see any way to open pre-existing worksheets within that workbook. Is there any way to do this?
You cannot append to an existing xlsx file with xlsxwriter.
There is a module called openpyxl which allows you to read and write to preexisting excel file, but I am sure that the method to do so involves reading from the excel file, storing all the information somehow (database or arrays), and then rewriting when you call workbook.close() which will then write all of the information to your xlsx file.
Similarly, you can use a method of your own to "append" to xlsx documents. I recently had to append to a xlsx file because I had a lot of different tests in which I had GPS data coming in to a main worksheet, and then I had to append a new sheet each time a test started as well. The only way I could get around this without openpyxl was to read the excel file with xlrd and then run through the rows and columns...
i.e.
cells = []
for row in range(sheet.nrows):
cells.append([])
for col in range(sheet.ncols):
cells[row].append(workbook.cell(row, col).value)
You don't need arrays, though. For example, this works perfectly fine:
import xlrd
import xlsxwriter
from os.path import expanduser
home = expanduser("~")
# this writes test data to an excel file
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home))
sheet1 = wb.add_worksheet()
for row in range(10):
for col in range(20):
sheet1.write(row, col, "test ({}, {})".format(row, col))
wb.close()
# open the file for reading
wbRD = xlrd.open_workbook("{}/Desktop/test.xlsx".format(home))
sheets = wbRD.sheets()
# open the same file for writing (just don't write yet)
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home))
# run through the sheets and store sheets in workbook
# this still doesn't write to the file yet
for sheet in sheets: # write data from old file
newSheet = wb.add_worksheet(sheet.name)
for row in range(sheet.nrows):
for col in range(sheet.ncols):
newSheet.write(row, col, sheet.cell(row, col).value)
for row in range(10, 20): # write NEW data
for col in range(20):
newSheet.write(row, col, "test ({}, {})".format(row, col))
wb.close() # THIS writes
However, I found that it was easier to read the data and store into a 2-dimensional array because I was manipulating the data and was receiving input over and over again and did not want to write to the excel file until it the test was over (which you could just as easily do with xlsxwriter since that is probably what they do anyway until you call .close()).
After searching a bit about the method to open the existing sheet in xlxs, I discovered
existingWorksheet = wb.get_worksheet_by_name('Your Worksheet name goes here...')
existingWorksheet.write_row(0,0,'xyz')
You can now append/write any data to the open worksheet.
You can use the workbook.get_worksheet_by_name() feature:
https://xlsxwriter.readthedocs.io/workbook.html#get_worksheet_by_name
According to https://xlsxwriter.readthedocs.io/changes.html the feature has been added on May 13, 2016.
"Release 0.8.7 - May 13 2016
-Fix for issue when inserting read-only images on Windows. Issue #352.
-Added get_worksheet_by_name() method to allow the retrieval of a worksheet from a workbook via its name.
-Fixed issue where internal file creation and modification dates were in the local timezone instead of UTC."
Although it is mentioned in the last two answers with it's documentation link, and from the documentation it seems indeed there are new methods to work with the "worksheets", I couldn't able to find this methods in the latest package of "xlsxwriter==3.0.3"
"xlrd" has removed support for anything other than xls files now.
Hence I was able to workout with "openpyxl" this gives you the expected functionality as mentioned in the first answer above.

Sort Column using openpyxl

I have created Excel sheet and written data into Excel file.
Do we have any functionality for sort column using openpyxl?
I could not attach Excel sheet and droping one row of excel sheet:
0 -269.9 99.97 0 -25.58 0 0.0006901 -269.9 127 0 26.23 0 810 -269.9
I'm pretty sure there is no such thing in openpyxl or xlwt or even xlsxwriter (but if you're on windows, you can do it via win32com and Excel.Application).
Usually, you should just read the data from the excel file, sort it in python and write the data back.
See similar questions:
how to sort xls file column wise and write it to another file with entire row using python?
xlrd / xlutils reordering spreadsheet rows

Categories

Resources