Написание данных разлива/массива для Excel с использованием OpenXML в C# заставляет клетку стать неотъемлемой частьюC#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Написание данных разлива/массива для Excel с использованием OpenXML в C# заставляет клетку стать неотъемлемой частью

Сообщение Anonymous »

Использование OpenXML для написания «разлива» или данных массива для Excel. Это данные, которые живет в одной ячейке, но переливаются в другие ячейки. Но если ячейка пуста или имеет одно значение, после того, как я запускаю свою программу и открываю .xlsx, формула издаренных ячеек обернута в дополнительную пару вьющихся скоб {}, и если я попытаюсь редактировать эту ячейку вообще, я получаю ошибку в Excel. src = "https://i.sstatic.net/1k0gsnb3.png"/>

Код: Выделить всё

public static void WriteSpillData(this WorksheetPart worksheetPart, string cellName, List data)
{
if(data.Count < 1) return;

var cell = worksheetPart.GetNamedCell(cellName);
if(cell is null) return;

var currentRef = cell?.CellFormula?.Reference;

if (!string.IsNullOrEmpty(currentRef))//if an existing spill existed this clears the cells of the old values
{
var range = worksheetPart.GetRange(CellReference.ParseRange(currentRef));

foreach (Cell existingCell in range)
{
if(existingCell is null ||
existingCell.CellReference.Value == cell.CellReference.Value) continue;

existingCell?.Remove();
}

}

//CellReference is just a helped class for converting between excels 1's based
//numbering convention for rows and columns and handle converting "B9" to a
//usable column and row number
CellReference reference = new CellReference(cell.CellReference.Value);
CellReference otherEnd = new CellReference(reference.Row, (reference.Column + data.Count - 1));

var refStr = $@"{reference}:{otherEnd}";

string arrayValue = string.Empty;
StringBuilder build = new StringBuilder();

if (IsNumeric(data.FirstOrDefault()))
{
build.Append("{");
build.Append(String.Join(',', data));
build.Append("}");
}
else
{

build.Append("{\"");
build.Append(String.Join("\",\"", data));
build.Append("\"}");

}

arrayValue = build.ToString();

cell.CellFormula = new CellFormula(arrayValue)
{
FormulaType = new EnumValue(CellFormulaValues.Array),
Reference = refStr,
AlwaysCalculateArray = true,

};

cell.CellValue?.Remove();

if (cell.Parent is Row row)
{
row.Spans = null;
row.RemoveAttribute("spans", "");
row.Spans = new ListValue { InnerText = $"1:{data.Count + 2}" };
}

worksheetPart.AddCellToCalcChain(cell.CellReference?.Value);
}

private static void AddCellToCalcChain(this WorksheetPart worksheet, string? cellReference)
{
if(string.IsNullOrEmpty(cellReference)) return;

// Use nullable type and null check to fix CS8600
WorkbookPart? workbookPart = worksheet.GetWorkbook();
if (workbookPart == null) return;

if (!(worksheet.GetSheetId() is uint sheetId)) return;

var calcChainPart = workbookPart.GetPartsOfType().FirstOrDefault();
if (calcChainPart == null)
{
calcChainPart = workbookPart.AddNewPart();
calcChainPart.CalculationChain = new CalculationChain();
}

// Create a new CalcCell and add it to the chain.
// You might want to check for an existing entry if necessary.
var calcCell = new CalculationCell
{
CellReference = cellReference,
Array = new BooleanValue(true),
NewLevel = new BooleanValue(true),
SheetId = new Int32Value((int)sheetId)
};
calcChainPart.CalculationChain.AppendChild(calcCell);

var childCalcCell = new CalculationCell
{
CellReference = cellReference,
SheetId = new Int32Value((int)sheetId),
InChildChain = new BooleanValue(true)
};
calcChainPart.CalculationChain.AppendChild(childCalcCell);

calcChainPart.CalculationChain.Save();
}
< /code>
Если я использую "tar -xf [.xlsx name здесь]" Я вижу основной XML. И после запуска моего кода я вижу изменения, которые я внесла в ячейку, ряд, Calcchain.  < /P>
//////from sheet2.xml


170


{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18}



/////from calcChain



Я взял электронную таблицу «чистый/пустой», добавил разлив/массив (= {0,1,2}) в одну ячейку, сохранен и рассеянный с помощью смолы. Я посмотрел, как Excel, кажется, справляется с массивом, и попытался имитировать это без повезло.

Подробнее здесь: https://stackoverflow.com/questions/797 ... -to-become
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»