c# - 打开 XML SDK : get "Unreadable content" error when trying to populate more than 25 columns

标签 c# spreadsheet openxml-sdk

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

当尝试填充第三个时,我在打开已完成的文档时遇到“不可读内容”错误,当我尝试在第三。

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

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;
    }
}

您可能想要更改字符串。比较为:

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

使用取自 this answer 的 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));
}

关于c# - 打开 XML SDK : get "Unreadable content" error when trying to populate more than 25 columns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14525573/

相关文章:

javascript - 在 Google 表格中跨行添加数字

excel-2007 - Excel "Refresh All"与 OpenXML

c# - WPF DataGrid 似乎没有虚拟化行

C# if (strValue == "FALSE"| strValue == "TRUE")

c# - LINQ to SQL调用存储过程

c# - 如何使用正则表达式忽略前面有特定字符串的字符串?

arrays - 如何从名称列中的每个单元格中提取姓氏并将其分配给名称数组?

javascript - 如何在 Javascript 中创建类似 excel 迷你图的内联条形图?

c# - 使用 OpenXML 2.5 将数据写入 docx 文档中的 TextInput 元素

openxml - 检索对评论 OpenXML 的引用