繁体   English   中英

Open XML SDK:尝试填充超过25列时出现“Unreadable content”错误

[英]Open XML SDK: get “Unreadable content” error when trying to populate more than 25 columns

我在C#中使用Open XML SDK创建了一个电子表格,并成功填充了两个工作表。

当尝试填充第三个时,我在打开完成的文档时出现“不可读内容”错误,并且当我尝试在第三个行中连续填充超过25个单元格时,它似乎发生。

我使用的代码片段与在文档中其他地方成功运行的代码片段相同:

string[] headers2 = {
    "Reference", "Raised", "Priority", "Affected", "Linked incidents",
    "Points", "SLA", "Stopped", "Target" };
// remaining headers are month/years created on the fly
string[] headerCells = {
    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
    "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", 
    "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH" };
...
// headers
// once we've finished the presets, the month/year pairs take over
cellNo = (uint)0;
foreach (string h in headers2)
{
    cell = InsertCellInWorksheet(headerCells[cellNo++], 2, worksheetPart);
    cell.CellValue = new CellValue(h);
    cell.DataType = new EnumValue<CellValues>(CellValues.String);
}

string[] monthYears = 
    GetData_month_years(currentReportingPeriod - 1);
for (int j = 0; j < monthYears.Count(); j++)
{
    cell = InsertCellInWorksheet(headerCells[cellNo++], 2, worksheetPart);
    cell.CellValue = new CellValue(monthYears[j].ToString());
    cell.DataType = new EnumValue<CellValues>(CellValues.String);
}

唯一填充的细胞是A和AA到AH。

我是否正确地认为我正在达到某种限制,如果是这样,重置它的方法是什么?

我看过几篇关于不可读内容错误的帖子,我查看了文档,但到目前为止我还没找到任何适用的内容。

帮助将不胜感激!

谢谢

接受的答案是定义正确的,但是是一种解决方法。 它只有在按顺序插入单元格时才有效。

如果您正在使用MSDN中的InsertCellInWorksheet方法,则在比较不同长度的单元格引用(如“Z”和“AA”)时,单元格引用上存在错误。

// Cells must be in sequential order according to CellReference. 
// Determine where to insert the new cell.
Cell refCell = null;
foreach (Cell cell in row.Elements<Cell>())
{
    if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
    {
        refCell = cell;
        break;
    }
}

您可能想要将string更改为:比较:

if (ColumnNameParse(cell.CellReference.Value) > ColumnNameParse(cellReference))
{
    refCell = cell;
    break;
}

使用从这个答案中获取的ColumnNameParse方法:

public int ColumnNameParse(string cellReference)
{
    var value = cellReference.TrimEnd("1234567890".ToCharArray());

    // assumes value.Length is [1,3]
    // assumes value is uppercase
    var digits = value.PadLeft(3).Select(x => "ABCDEFGHIJKLMNOPQRSTUVWXYZ".IndexOf(x));
    return digits.Aggregate(0, (current, index) => (current * 26) + (index + 1));
}

请查看“InsertCellInWorksheet(...)”方法。 如果你在里面使用这种结构 -

...

row.InsertBefore(newCell, refCell);

...

如果要填写“A - Z”和“AA - ...”列,即使您只想填写两列(例如), - “Z”和“AA”,它也无法正常工作。 因此,请尝试使用此方法:

...
row.Append(newCell);
...

祝好运!

更改

if (string.Compare(cell.CellReference.Value, cellReference, true) > 0) 

if (string.Compare(cell.CellReference.Value, cellReference, true) > 0
                        && cell.CellReference.Value.Length >= cellReference.Length)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM