How to edit Excel file (xlsx) using linux shell

11

2

Is there a way (tool) to edit XLSX files using Linux shell? What I need is a way to remove the last three not empty rows from the first worksheet.

I know that XLSX is just a zip file, packed with different XML files, which I could individually edit. However, I would like to avoid analyzing and changing the XML files myself, if possible.

Bojan Hrnkas

Posted 2018-07-10T13:26:29.137

Reputation: 2 072

Answers

14

My idea is a python script like this:

import pandas as pd
filename=argv[1]
df = pd.read_excel(filename,sheet_name="Sheet1").ix[:-3] ## read the xlsx without last 3 rows to a dataframe
df.write_excel("output_sheet.xlsx") #write dataframe to xlsx file

to check "non-emptiness" you can use df.notna()

DDS

Posted 2018-07-10T13:26:29.137

Reputation: 514

Sounds promising - will give it a try.

Just to be sure - df.ix[:-3] - will delete last three not empty rows? Because an excel sheet has a lot of empty rows, if you look at the xml file in the xlsx. – Bojan Hrnkas – 2018-07-10T13:53:11.697

2

it deletes last 3 rows. empty rows after last non empty row are ignored. For convenience here: https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.DataFrame.html is a reference of pandas dataframe

– DDS – 2018-07-10T13:55:22.643

-3

Libreoffice (and probably also OpenOffice) can read .xlsx files created by Excel. If you don't have a lot of files to process in this way, doing it manually in Libreoffice is the simplest way to go. If you have a lot of files, and really need an automated solution, Libreoffice is scriptable. See the API docs or start with a more tutorial introduction.

Nick

Posted 2018-07-10T13:26:29.137

Reputation: 5

2This doesn't work for me, because I want to automate something on a headless server. – Bojan Hrnkas – 2018-07-10T17:38:12.487

You should edit your question too specify all your constraints / requirements. – Scott – 2018-07-10T17:45:35.067

2@pipe. It is possible to run LibreOffice in headless mode, is it not? – TRiG – 2018-07-10T20:45:11.303

3@TRiG Sure it is, and an answer detailing how to do that would be a great answer. This is not that answer. – pipe – 2018-07-10T20:52:37.553

1@pipe calling LibreOffice a "one-off gui tool" is pretty extreme. It's basically the opposite of what it really is. – barbecue – 2018-07-10T23:42:08.493

1Opening LibreOffice in Headless mode is as simple as using the --headless option. – Johnny – 2018-07-11T07:15:50.193