我在 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/