Skip to content

Instantly share code, notes, and snippets.

@evanrrees
Last active January 19, 2022 10:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evanrrees/a867574a7787724df51a451eaddac38b to your computer and use it in GitHub Desktop.
Save evanrrees/a867574a7787724df51a451eaddac38b to your computer and use it in GitHub Desktop.
Remove sheet protections in Excel workbooks
#!/usr/bin/env bash
# Evan Rees
# err87@cornell.edu
# August 2021
# Remove sheet protections from .xlsx or .xls files
usage() {
cat <<EOF
Remove sheet protections from Excel worksheets.
Usage: $0 FILE [...]
EOF
}
if (( $# == 0 )); then
usage
exit 1
elif [[ "$1" =~ -h|--help|-help|help ]]; then
usage
exit 0
fi
unprotect() {
set -eu
local PREFIX EXTENSION
EXTENSION="$(sed -E 's/.+\.//' <<< $FILENAME)"
PREFIX="$(sed -E 's/(\.xlsx|\.xls)$//' <<< $FILENAME)"
if ! [[ "$EXTENSION" =~ xlsx|xls ]]; then
printf "Failed (not an Excel file)\n"
return 1
fi
unzip -qd "$PREFIX" "$FILENAME"
cd "$PREFIX"
find "xl/worksheets" -maxdepth 1 -type f -regex ".+sheet[0-9]+\.xml" -exec sed -Ei 's/<sheetProtection[^>]+>//' {} \;
zip -qr "../${PREFIX}.unprotected.${EXTENSION}" .
cd ..
rm -r "$PREFIX"
set +eu
}
for FILENAME in "$@"; do
printf "Processing %s...\t" "$FILENAME"
unprotect "$FILENAME"
EXIT_STATUS=$?
if (( $EXIT_STATUS == 0 )); then
printf "%s\n" "Success"
else
printf "%s (%d)\n" "Failed" $EXIT_STATUS
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment