Добавление одной таблицы в другую с использованием NPOI с включенным CellStyling
Я пытаюсь прочитать один файл и добавить его в другой с включенным стилем ячейки. Кажется, что все проблемы проистекают из внутреннего цикла foreach, и я пометил звездочкой строку, сообщающую об ошибке. Проблема с этим кодом заключается в том, что:
Произошло необработанное исключение типа "System.ArgumentException" в NPOI.OOXML.dll Дополнительная информация: Этот стиль не относится к предоставленному источнику стилей книги. Вы пытаетесь присвоить стиль из одной рабочей книги ячейке другой рабочей книги?
private void AddCellFooter(ref ISheet quoteSheet,string brandName, int lastRowIndex, ref IWorkbook quoteWorkbook )
{
FileStream sw = null;
if (File.Exists("Quote Templates\\" + brandName + "MasterFooter.xlsx"))
{
IRow currentRow;
ICell currentCell;
ICellStyle currentStyle;
int cellIndex;
sw = File.OpenRead("Quote Templates\\" + brandName + "MasterFooter.xlsx");
IWorkbook footerWorkBook = WorkbookFactory.Create(sw);
ISheet footerSheet = footerWorkBook.GetSheet("Sheet1");
foreach (IRow footerRow in footerSheet)
{
cellIndex = 0;
currentRow = quoteSheet.CreateRow(lastRowIndex);
foreach (ICell footerCell in footerRow)
{
currentCell = currentRow.CreateCell(cellIndex,footerCell.CellType);
currentCell.SetCellValue(footerCell.StringCellValue);
currentStyle = quoteWorkbook.CreateCellStyle();
currentStyle = footerCell.CellStyle;
******currentCell.CellStyle = currentStyle;******
cellIndex++;
}
lastRowIndex++;
}
sw.Close();
}
}
Для этого нужно прочитать все ячейки электронной таблицы нижнего колонтитула и записать их в кавычку. Первые две строки цикла foreach работают нормально, поэтому я могу написать текст в нижнем колонтитуле, но не могу найти способ сохранить стили при копировании.
Я попытался установить цикл foreach, чтобы просто
foreach (ICell footerCell in footerRow)
{
currentCell = currentRow.CreateCell(cellIndex,footerCell.CellType);
currentCell = footerCell;
cellIndex++;
}
Но это только произвело пустые клетки. Любая помощь будет принята с благодарностью, спасибо
1 ответ
Если кому-то это понадобится в будущем, это будет работать правильно: (footerHeight и footerWidth - это размеры добавляемой таблицы)
for (int i = 0; i < footerHeight; i++)
{
currentRow = quoteSheet.CreateRow(i + lastRowIndex);
for (int j = 0; j < footerWidth; j++)
{
CellType ct = footerSheet.GetRow(i).GetCell(j)?.CellType ?? CellType.Blank;
if (ct != CellType.Unknown)
{
ICell footerCell = footerSheet.GetRow(i).GetCell(j);
switch (ct)
{
case CellType.Unknown:
break;
case CellType.Numeric:
currentCell = currentRow.CreateCell(j, CellType.Numeric);
currentCell.SetCellValue(footerCell.NumericCellValue);
break;
case CellType.String:
currentCell = currentRow.CreateCell(j, CellType.String);
currentCell.SetCellValue(footerCell.StringCellValue);
break;
case CellType.Formula:
break;
case CellType.Blank:
currentCell = currentRow.CreateCell(j, CellType.String);
currentCell.SetCellValue("");
break;
case CellType.Boolean:
break;
case CellType.Error:
break;
default:
break;
}
currentStyle = quoteWorkbook.CreateCellStyle();
if (footerCell != null)
{
currentStyle.CloneStyleFrom(footerCell.CellStyle);
}
currentCell.CellStyle = currentStyle;
}
}
}
С основной новой функцией
currentStyle.CloneStyleFrom(footerCell.CellStyle);
Очевидно, что CellStyles довольно сложны, поэтому для копирования между рабочими книгами требуется специальная команда.