Last active
January 19, 2022 10:05
-
-
Save evanrrees/a867574a7787724df51a451eaddac38b to your computer and use it in GitHub Desktop.
Remove sheet protections in Excel workbooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Evan Rees | |
# [email protected] | |
# 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