Valid characters for Excel sheet names

后端 未结 4 1680
谎友^
谎友^ 2020-12-09 15:04

In Java, we\'re using the following package to programmatically create excel documents:

org.apache.poi.hssf

If you attempt to set a sheet\'

相关标签:
4条回答
  • 2020-12-09 15:39

    This is what I use in C# (should be similar in Java):

    const string invalidCharsRegex = @"[/\\*'?[\]:]+";
    const int maxLength = 31;
    
    string safeName = Regex.Replace(worksheetName, invalidCharsRegex, " ")
                            .Replace("  ", " ")
                            .Trim();
    
    if (string.IsNullOrEmpty(safeName))
    {
        safeName = "Default";   // cannot be empty
    }
    else if (safeName.Length > maxLength)
    {
        safeName = safeName.Substring(0, maxLength);
    }
    
    0 讨论(0)
  • 2020-12-09 15:41

    You can use this:

    protected Sheet createSheet(XSSFWorkbook book, String nameSheet) {
        return book.createSheet(WorkbookUtil.createSafeSheetName(nameSheet));
    }
    
    0 讨论(0)
  • 2020-12-09 15:44

    You can use the Apache POI's WorkbookUtil.createSafeSheetName(String s) to safely create your Sheet Name.

    http://poi.apache.org/apidocs/org/apache/poi/ss/util/WorkbookUtil.html

    0 讨论(0)
  • 2020-12-09 15:50

    I think the problem is the colon, not the exclamation point.

    If you open Excel and try to manually edit a sheet name, the only characters it doesn't let you type are [ ] * / \ ? :

    If you paste one of those characters in, you get the following error: (Excel 2003)

    While renaming a sheet or chart, you entered an invalid name. Try one of the following:

    • Make sure the name you entered does not exceed 31 characters.
    • Make sure the name does not contain any of the following characters: : \ / ? * [ or ]
    • Make sure you did not leave the name blank.
    0 讨论(0)
提交回复
热议问题