2 Commits

Author SHA1 Message Date
melekhin
eccb12b83c Text() debug
All checks were successful
Publish NuGet packages / publish (push) Successful in 25s
2026-06-16 15:52:08 +07:00
melekhin
804fc84563 ICellText rename
All checks were successful
Publish NuGet packages / publish (push) Successful in 26s
2026-06-16 12:03:56 +07:00
3 changed files with 49 additions and 27 deletions

View File

@@ -426,15 +426,34 @@ internal sealed class ExcelCell : ICell
} }
/// <inheritdoc /> /// <inheritdoc />
public ICellText? Text() public ICellText Text()
{ {
_writer.ThrowIfDisposed(); _writer.ThrowIfDisposed();
lock (_writer._syncLock) lock (_writer._syncLock)
{ {
var cell = GetCellElement(); // 1. Получаем или создаём элемент ячейки
if (cell == null || cell.DataType?.Value != CellValues.InlineString || cell.InlineString == null) var cell = GetOrCreateCellElement();
return null;
// 2. Убедимся, что у ячейки правильный тип и есть InlineString
if (cell.DataType == null || cell.DataType.Value != CellValues.InlineString)
{
// Если был другой тип (например, число) — меняем на InlineString
cell.DataType = CellValues.InlineString;
// Удаляем старый InlineString, если был
cell.InlineString?.Remove();
// Создаём новый пустой InlineString
cell.InlineString = new InlineString();
// Добавляем пустой Text (обязательно для Open XML)
cell.InlineString.AppendChild(new Text());
}
else if (cell.InlineString == null)
{
// Если тип InlineString, но сам элемент отсутствует
cell.InlineString = new InlineString();
cell.InlineString.AppendChild(new Text());
}
// 3. Строим объект ICellText на основе содержимого InlineString
var textObj = new ExcelCellText(); var textObj = new ExcelCellText();
foreach (var run in cell.InlineString.Elements<Run>()) foreach (var run in cell.InlineString.Elements<Run>())
{ {
@@ -442,11 +461,14 @@ internal sealed class ExcelCell : ICell
RunFormat? format = null; RunFormat? format = null;
if (run.RunProperties != null) if (run.RunProperties != null)
{ {
// Преобразуем RunProperties в RunFormat (можно вынести в отдельный метод)
format = RunFormat.FromRunProperties(run.RunProperties); format = RunFormat.FromRunProperties(run.RunProperties);
} }
textObj.AddRun(text, format); textObj.Run(text, format);
} }
// Если не было ни одного Run, текст всё равно должен быть доступен (пустой)
// Можно оставить textObj пустым, а можно сразу добавить пустой Run
// (но это не обязательно пользователь может добавить run позже)
return textObj; return textObj;
} }
} }

View File

@@ -94,7 +94,7 @@ internal sealed class ExcelCellText : ICellText
} }
/// <inheritdoc /> /// <inheritdoc />
public ICellText AddBreak() public ICellText Break()
{ {
// Добавляем символ переноса строки в последний существующий Run // Добавляем символ переноса строки в последний существующий Run
if (_runs != null && _runs.Count > 0) if (_runs != null && _runs.Count > 0)
@@ -105,13 +105,13 @@ internal sealed class ExcelCellText : ICellText
else else
{ {
// Если нет ни одного Run, создаём новый с символом переноса // Если нет ни одного Run, создаём новый с символом переноса
AddRun("\n", null); Run("\n", null);
} }
return this; return this;
} }
/// <inheritdoc /> /// <inheritdoc />
public ICellText AddRun(string text, RunFormat? format = null) public ICellText Run(string text, RunFormat? format = null)
{ {
if (string.IsNullOrEmpty(text)) if (string.IsNullOrEmpty(text))
return this; return this;
@@ -122,15 +122,15 @@ internal sealed class ExcelCellText : ICellText
} }
/// <inheritdoc /> /// <inheritdoc />
public ICellText AddRunBreak(string text, RunFormat? format = null) public ICellText RunBreak(string text, RunFormat? format = null)
{ {
AddRun(text, format); Run(text, format);
AddBreak(); Break();
return this; return this;
} }
/// <inheritdoc /> /// <inheritdoc />
public ICellText AddSubRun(string text, RunFormat? format = null) public ICellText Sub(string text, RunFormat? format = null)
{ {
var subFormat = format is { } fmt var subFormat = format is { } fmt
? new RunFormat ? new RunFormat
@@ -145,11 +145,11 @@ internal sealed class ExcelCellText : ICellText
Vertical = VerticalTextRunAlignment.Subscript Vertical = VerticalTextRunAlignment.Subscript
} }
: new RunFormat { Vertical = VerticalTextRunAlignment.Subscript }; : new RunFormat { Vertical = VerticalTextRunAlignment.Subscript };
return AddRun(text, subFormat); return Run(text, subFormat);
} }
/// <inheritdoc /> /// <inheritdoc />
public ICellText AddSupRun(string text, RunFormat? format = null) public ICellText Sup(string text, RunFormat? format = null)
{ {
var supFormat = format is { } fmt var supFormat = format is { } fmt
? new RunFormat ? new RunFormat
@@ -164,7 +164,7 @@ internal sealed class ExcelCellText : ICellText
Vertical = VerticalTextRunAlignment.Subscript Vertical = VerticalTextRunAlignment.Subscript
} }
: new RunFormat { Vertical = VerticalTextRunAlignment.Superscript }; : new RunFormat { Vertical = VerticalTextRunAlignment.Superscript };
return AddRun(text, supFormat); return Run(text, supFormat);
} }
/// <inheritdoc /> /// <inheritdoc />
@@ -186,14 +186,14 @@ internal sealed class ExcelCellText : ICellText
if (!TryInsertRun(index, text, format)) if (!TryInsertRun(index, text, format))
return false; return false;
// После вставленного run добавляем break на следующей позиции // После вставленного run добавляем break на следующей позиции
AddBreak(); Break();
// Сдвигаем? Просто добавляем break в конец неверно. Break должен быть сразу после вставленного. // Сдвигаем? Просто добавляем break в конец неверно. Break должен быть сразу после вставленного.
// Но AddBreak добавляет в конец. Нужно вставить break на index+1. // Но AddBreak добавляет в конец. Нужно вставить break на index+1.
return TryInsertRun(index + 1, "\n", null); return TryInsertRun(index + 1, "\n", null);
} }
/// <inheritdoc /> /// <inheritdoc />
public bool TryInsertSubRun(int index, string text, RunFormat? format = null) public bool TryInsertSub(int index, string text, RunFormat? format = null)
{ {
var subFormat = format is { } fmt var subFormat = format is { } fmt
? new RunFormat ? new RunFormat
@@ -212,7 +212,7 @@ internal sealed class ExcelCellText : ICellText
} }
/// <inheritdoc /> /// <inheritdoc />
public bool TryInsertSupRun(int index, string text, RunFormat? format = null) public bool TryInsertSup(int index, string text, RunFormat? format = null)
{ {
var supFormat = format is { } fmt var supFormat = format is { } fmt
? new RunFormat ? new RunFormat

View File

@@ -706,7 +706,7 @@ public interface ICell
bool TryText(out ICellText cellText); bool TryText(out ICellText cellText);
/// <summary>Возвращает объект для редактирования богатого текста ячейки (если ячейка содержит InlineString).</summary> /// <summary>Возвращает объект для редактирования богатого текста ячейки (если ячейка содержит InlineString).</summary>
ICellText? Text(); ICellText Text();
/// <summary>Устанавливает простое текстовое значение (без форматирования).</summary> /// <summary>Устанавливает простое текстовое значение (без форматирования).</summary>
ICell Set(string value); ICell Set(string value);
@@ -779,19 +779,19 @@ public interface ICellText
bool TryRemoveRun(int index, out IRun? removed); bool TryRemoveRun(int index, out IRun? removed);
/// <summary>Добавляет разрыв строки (перенос внутри ячейки).</summary> /// <summary>Добавляет разрыв строки (перенос внутри ячейки).</summary>
ICellText AddBreak(); ICellText Break();
/// <summary>Добавляет обычный текстовый фрагмент.</summary> /// <summary>Добавляет обычный текстовый фрагмент.</summary>
ICellText AddRun(string text, RunFormat? format = null); ICellText Run(string text, RunFormat? format = null);
/// <summary>Добавляет фрагмент с последующим разрывом строки.</summary> /// <summary>Добавляет фрагмент с последующим разрывом строки.</summary>
ICellText AddRunBreak(string text, RunFormat? format = null); ICellText RunBreak(string text, RunFormat? format = null);
/// <summary>Добавляет подстрочный фрагмент (эквивалентно AddRun с Vertical = Subscript).</summary> /// <summary>Добавляет подстрочный фрагмент (эквивалентно AddRun с Vertical = Subscript).</summary>
ICellText AddSubRun(string text, RunFormat? format = null); ICellText Sub(string text, RunFormat? format = null);
/// <summary>Добавляет надстрочный фрагмент.</summary> /// <summary>Добавляет надстрочный фрагмент.</summary>
ICellText AddSupRun(string text, RunFormat? format = null); ICellText Sup(string text, RunFormat? format = null);
/// <summary>Вставляет фрагмент по индексу.</summary> /// <summary>Вставляет фрагмент по индексу.</summary>
bool TryInsertRun(int index, string text, RunFormat? format = null); bool TryInsertRun(int index, string text, RunFormat? format = null);
@@ -800,10 +800,10 @@ public interface ICellText
bool TryInsertRunBreak(int index, string text, RunFormat? format = null); bool TryInsertRunBreak(int index, string text, RunFormat? format = null);
/// <summary>Вставляет подстрочный фрагмент по индексу.</summary> /// <summary>Вставляет подстрочный фрагмент по индексу.</summary>
bool TryInsertSubRun(int index, string text, RunFormat? format = null); bool TryInsertSub(int index, string text, RunFormat? format = null);
/// <summary>Вставляет надстрочный фрагмент по индексу.</summary> /// <summary>Вставляет надстрочный фрагмент по индексу.</summary>
bool TryInsertSupRun(int index, string text, RunFormat? format = null); bool TryInsertSup(int index, string text, RunFormat? format = null);
/// <summary>Применяет заданный формат ко всем существующим фрагментам (поверх их текущего форматирования, заменяя неуказанные свойства).</summary> /// <summary>Применяет заданный формат ко всем существующим фрагментам (поверх их текущего форматирования, заменяя неуказанные свойства).</summary>
void ApplyFormatToAllRuns(RunFormat format); void ApplyFormatToAllRuns(RunFormat format);