Unreadable content in Excel file generated with EPPlus

前端 未结 7 975
谎友^
谎友^ 2021-01-04 02:57

I\'m having a little problem when I generate an Excel file from a template, using the EPPlus library. The file has a first spreadsheet that contains data that is used for po

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-04 03:39

    The problem is not solved but now I know exactly why. This "Table1" thing wasn't a named range but a table, which I can access through the "Tables" collection of the worksheet.

    Now, the problem is that both the Tables' collection and Table objects in EPPlus are readonly so I can't define the table's dimension from my code, and neither can I remove it or add a new one to fit my needs. EPPlus's author has already mentionned that it might someday be implemented (here and here) bus as the messages are almost 3 years old, I guess there is little hope to see that happen...

    Anyway, I hope this will help anyone encountering the same issue.

    [EDIT] I finally came up with a way to bypass the problem : the ExcelTable object has a writable property called "TableXml" which contains the xml definition of the table with - of course - its range. Here's its content in my case :

    
        
            
                
                
                [...]
                
            
            
    

    What interests us here are the "ref" attributes in the "table" and "autoFilter" nodes, as changing their values allows to redefine the range of our table.

    I proceeded this way :

    XmlDocument tabXml = sheet.Tables(0).TableXml;
    XmlNode tableNode = tabXml.ChildNodes[1];
    tableNode.Attributes["ref"].Value = string.Format("A1:U{0}", dt.Rows.Count + 1);
    XmlNode autoFilterNode = tableNode.ChildNodes[0];
    autoFilterNode.Attributes["ref"].Value = string.Format("A1:U{0}", dt.Rows.Count + 1);
    

    And now my Excel file is properly generated with "Table1" fitting the actual range of my data !

提交回复
热议问题