2

I'm doing some testing using python-excel modules. I can't seem to find a way to delete a row in an excel sheet using these modules and the internet hasn't offered up a solution. Is there a way to delete a row using one of the python-excel modules?

In my case, I want to open an excel sheet, read the first row, determine if it contains some valid data, if not, then delete it.

Any suggestions are welcome.

3 Answers 3

2

xlwt provides as the module name suggests Excel writer (creation rather than modification) funcionality. xlrd on the other hand provides Excel reader funcionality.

If your source excel file is rather simple (no fancy graphs, pivot tables, etc.), you should proceed this way:

with xlrd module read the contents of the targeted excel file, and then with xlwt module create new excel file which contains the necessary rows.

If you, however are running this on windows platform , you might be able to manipulate Excel directly through Microsoft COM objects, see old book reference.

Sign up to request clarification or add additional context in comments.

1 Comment

Thansk for the suggestion jbreicis!
2

I was having the same issue but found a walk around:

  1. Use a custom filter process (Reader>Filter1>Filter2>...>Writer) to generate a copy of the source excel file but with a blank column inserted at the front. Let's call this file augmented.xls.

  2. Then, read augmented.xls into a xlrd.Workbook object, rb, using xlrd.open_workbook().

  3. Use xlutils.copy.copy() to convert rb into a xlwt.Workbook object, wb.

  4. Set the value of the first column of each of the to-be-deleted rows as "x" (or other values as a marker) in wb.

  5. Save wb back to augmented.xls.

  6. Use another custom filter process to generate a resulting excel file from augmented.xls by omitting those rows with "x" in the first column and shifting all columns one column left (equivalent to deleting the first column of markers).

Information and examples of defining a filter process can be found in http://www.simplistix.co.uk/presentations/python-excel.pdf

Hope this help in some way.

Comments

0

You can use the library openpyxl. When opening a file it is both for reading and for writing. Then, with a simple function you can achieve that:

from openpyxl import load_workbook

wb = load_workbook(filename)

ws = wb.active()

first_row = ws[1]

# Your code here using first_row

if first_row not valid:
    ws.delete_rows(1, amount=1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.