Skip to content

Instantly share code, notes, and snippets.

@scottj
Last active February 17, 2023 21:02
Show Gist options
  • Save scottj/1940d387444a33525e859e0f25b084ed to your computer and use it in GitHub Desktop.
Save scottj/1940d387444a33525e859e0f25b084ed to your computer and use it in GitHub Desktop.
Unprotect Excel Files
#!/usr/bin/env bash
if [[ $# -lt 2 ]]; then printf "Usage:\n$0 <src> <dst>\n"; exit; fi
function abspath { # https://stackoverflow.com/a/23002317/226502
if [[ -d $1 ]]; then (cd "$1"; pwd)
else
if [[ $1 = /* ]]; then echo "$1"
elif [[ $1 == */* ]]; then echo "$(cd "${1%/*}"; pwd)/${1##*/}"
else echo "$(pwd)/$1"
fi
fi
}
# get absolute filenames, test for input file existence
infile=$(abspath "$1")
if [[ ! -f $infile ]]; then
echo "ERROR: input file not found"
exit 1
fi
outfile=$(abspath "$2")
# unzip into temp folder
tmpdir=$(mktemp -d /tmp/unprotect.XXXXXX)
unzip -q "$infile" -d "$tmpdir"
# edit files
sed -e 's/<workbookProtection[^>]*>//' -i .backup ${tmpdir}/xl/workbook.xml
for f in $(grep -rl sheetProtection ${tmpdir}); do
sed -e 's/<sheetProtection[^>]*>//' -i .backup $f
done
if [[ ! -z $3 ]]; then read -p "Press enter to continue"; fi
# create new zip
pushd $tmpdir > /dev/null
zip -qr9 -x*.backup "$outfile" *
popd > /dev/null
rm -rf "$tmpdir"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment