follow-on to r1294180

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1294186 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Yegor Kozlov 2012-02-27 15:29:26 +00:00
parent be4f4d11a8
commit d52b24dae0
1 changed files with 54 additions and 31 deletions

View File

@ -45,40 +45,63 @@ public class WorkbookUtil {
* @return a valid string, "empty" if to short, "null" if null * @return a valid string, "empty" if to short, "null" if null
*/ */
public final static String createSafeSheetName(final String nameProposal) { public final static String createSafeSheetName(final String nameProposal) {
if (nameProposal == null) { return createSafeSheetName(nameProposal, ' ');
return "null"; }
}
if (nameProposal.length() < 1) { /**
return "empty"; * Creates a valid sheet name, which is conform to the rules.
} * In any case, the result safely can be used for
final int length = Math.min(31, nameProposal.length()); * {@link org.apache.poi.ss.usermodel.Workbook#setSheetName(int, String)}.
final String shortenname = nameProposal.substring(0, length); * <br>
final StringBuilder result = new StringBuilder(shortenname); * Rules:
for (int i=0; i<length; i++) { * <ul>
char ch = result.charAt(i); * <li>never null</li>
switch (ch) { * <li>minimum length is 1</li>
* <li>maximum length is 31</li>
* <li>doesn't contain special chars: : 0x0000, 0x0003, / \ ? * ] [ </li>
* <li>Sheet names must not begin or end with ' (apostrophe)</li>
* </ul>
*
* @param nameProposal can be any string, will be truncated if necessary,
* allowed to be null
* @param replaceChar the char to replace invalid characters.
* @return a valid string, "empty" if to short, "null" if null
*/
public final static String createSafeSheetName(final String nameProposal, char replaceChar) {
if (nameProposal == null) {
return "null";
}
if (nameProposal.length() < 1) {
return "empty";
}
final int length = Math.min(31, nameProposal.length());
final String shortenname = nameProposal.substring(0, length);
final StringBuilder result = new StringBuilder(shortenname);
for (int i=0; i<length; i++) {
char ch = result.charAt(i);
switch (ch) {
case '\u0000': case '\u0000':
case '\u0003': case '\u0003':
case ':': case ':':
case '/': case '/':
case '\\': case '\\':
case '?': case '?':
case '*': case '*':
case ']': case ']':
case '[': case '[':
result.setCharAt(i, ' '); result.setCharAt(i, replaceChar);
break; break;
case '\'': case '\'':
if (i==0 || i==length-1) { if (i==0 || i==length-1) {
result.setCharAt(i, ' '); result.setCharAt(i, replaceChar);
} }
break; break;
default: default:
// all other chars OK // all other chars OK
} }
} }
return result.toString(); return result.toString();
} }
/** /**
* Validates sheet name. * Validates sheet name.