Saxonite 1.2.11.2

This commit is contained in:
Andy Howard
2024-02-27 15:45:02 +00:00
parent f3350fdc23
commit 2239f37408
54 changed files with 3613 additions and 1175 deletions
+295 -153
View File
@@ -4,6 +4,10 @@ using Sarand.Net.Standard.Base.Core;
using Sarand.Net.Standard.Base.Bus;
using Sarand.Net.Standard.Base.App;
using Sarand.Net.Standard.Base.Utils;
using DocumentFormat.OpenXml.Spreadsheet;
using NPOI.SS.UserModel;
using NPOI.SS.Formula.Functions;
using System.Text.RegularExpressions;
namespace Sarand.Net.Standard.Proc.Excel
{
@@ -16,24 +20,24 @@ namespace Sarand.Net.Standard.Proc.Excel
//=======================================================================
public class SaMsExcelRange
{
public uint ColFrom { get; set; } = 0;
public uint ColTo { get; set; } = 0;
public uint RowFrom { get; set; } = 0;
public uint RowTo { get; set; } = 0;
public uint ColFromPos { get; set; } = 0;
public uint ColToPos { get; set; } = 0;
public uint RowFromPos { get; set; } = 0;
public uint RowToPos { get; set; } = 0;
public SaMsExcelRange() { }
public SaMsExcelRange(uint colPos, uint rowPos)
{
ColFrom = colPos;
ColTo = colPos;
RowFrom = rowPos;
RowTo = rowPos;
ColFromPos = colPos;
ColToPos = colPos;
RowFromPos = rowPos;
RowToPos = rowPos;
}
public SaMsExcelRange(uint colPosFrom, uint rowPosFrom, uint colPosTo, uint rowPosTo)
{
ColFrom = colPosFrom;
ColTo = colPosTo;
RowFrom = rowPosFrom;
RowTo = rowPosTo;
ColFromPos = colPosFrom;
ColToPos = colPosTo;
RowFromPos = rowPosFrom;
RowToPos = rowPosTo;
}
}
//=======================================================================
@@ -78,17 +82,29 @@ namespace Sarand.Net.Standard.Proc.Excel
//=======================================================================
public class SaMsExcelColumnHeading_Config
{
public double ColumnWidthPixelsPerCm { get; set; } = 43.0; // Between 10 and 100
public uint FirstHeadingRow { get; set; } = 1; // Must be > 0
public uint FirstHeadingColumn { get; set; } = 1; // Must be > 0
public uint FreezeColumn { get; set; } = 0; // 0 = don't freeze
public short HeadingFontSize { get; set; } = 9;
public bool HeadingTextBold { get; set; } = true;
public bool HeadingTextWrap { get; set; } = true;
/// <summary>Cell font colour index, ref. XlColorIndex</summary>
public SaXlColourIndex InteriorColourIndex { get; set; } = SaXlColourIndex.NotSpecified;
/// <summary>Cell RGB colour value, ref. XlRgbColor. Overrides colour index if changed from default value.</summary>
public int? InteriorColour { get; set; } = null;
// Heading configuration.
/// <summary>Pixels per cm. Default 43. Min 10, max 100.</summary>
public double ColumnWidthPixelsPerCm { get; set; } = 43.0;
/// <summary>First heading column position (from 1). Default 1. Must be > 0.</summary>
public uint FirstHeadingColPos { get; set; } = 1;
/// <summary>First heading row position (from 1). Default 1. Must be > 0.</summary>
public uint FirstHeadingRowPos { get; set; } = 1;
/// <summary>First data row position. Reset by SetColumnHeadings().</summary>
public uint FirstDataRowPos { get; set; } = 2;
/// <summary>Freeze column position - cell in first data row. 0 = don't freeze.</summary>
public uint FreezeColPos { get; set; } = 0;
/// <summary>Font attributes. Default Arial 9 bold.</summary>
public SaMsExcelFontAttr FontAttr { get; } = new SaMsExcelFontAttr() { Name = "Arial", HeightInPoints = 9, Bold = true };
/// <summary>Whether to wrap column header cells.</summary>
public bool HeadingTextWrap { get; set; } = false;
/// <summary>Cell vertical alignment. XlVAlign.xlTop, xlCenter, xlBottom, xlJustify, xlDistributed etc.</summary>
public short? VerticalAlignment { get; set; } = null;
/// <summary>Cell foreground colour index, ref. XlColorIndex</summary>
public SaXlColourIndex ForegroundColourIndex { get; set; } = SaXlColourIndex.NotSpecified;
/// <summary>Cell foreground RGB colour value, ref. XlRgbColor. Overrides foreground colour index if changed from default value.</summary>
public int? ForegroundColourRGB { get; set; } = null;
/// <summary>Cell background colour index, ref. XlColorIndex</summary>
public SaXlColourIndex BackgroundColourIndex { get; set; } = SaXlColourIndex.NotSpecified;
public SaXlBorderWeight BorderWeight { get; set; } = SaXlBorderWeight.NotSpecified;
public bool SetColumnWidths { get; set; } = true;
public bool SetColumnAlignment { get; set; } = true;
@@ -147,29 +163,55 @@ namespace Sarand.Net.Standard.Proc.Excel
public class SaMsExcelFontAttr
{
/// <summary>Font name. Arial etc.</summary>
public String FontName { get; set; } = String.Empty;
public String Name { get; set; } = String.Empty;
/// <summary>Font style. Regular etc.</summary>
public String FontStyle { get; set; } = String.Empty;
public short? FontSize { get; set; } = null;
public double? HeightInPoints { get; set; } = null;
/// <summary>Font colour index, ref. XlColorIndex.</summary>
public SaXlColourIndex FontColourIndex { get; set; } = SaXlColourIndex.NotSpecified;
/// <summary>Font RGB colour value, ref. XlRgbColor. Overrides colour index if changed from default value.</summary>
public int? FontColor { get; set; } = null;
public SaXlColourIndex ColourIndex { get; set; } = SaXlColourIndex.NotSpecified;
/// <summary>Font RGB colour value, ref. XlRgbColor.</summary>
public int? ColourRGB { get; set; } = null;
public bool? Bold { get; set; } = null;
public bool? Strikethrough { get; set; } = null;
public bool? Superscript { get; set; } = null;
public bool? Subscript { get; set; } = null;
public bool? OutlineFont { get; set; } = null;
public bool? Outline { get; set; } = null;
public bool? Shadow { get; set; } = null;
public SaXlUnderlineStyle? Underline { get; set; } = null;
public void CopyFrom(SaMsExcelFontAttr fontAttr)
{
Name = fontAttr.Name;
FontStyle = fontAttr.FontStyle;
HeightInPoints = fontAttr.HeightInPoints;
ColourIndex = fontAttr.ColourIndex;
ColourRGB = fontAttr.ColourRGB;
Bold = fontAttr.Bold;
Strikethrough = fontAttr.Strikethrough;
Superscript = fontAttr.Superscript;
Subscript = fontAttr.Subscript;
Outline = fontAttr.Outline;
Shadow = fontAttr.Shadow;
Underline = fontAttr.Underline;
}
public bool IsSpecified()
{
if (HeightInPoints != null && HeightInPoints >= SaMsSpreadsheet.FontHeightInPointsMin && HeightInPoints <= SaMsSpreadsheet.FontHeightInPointsMax) return true;
if (ColourRGB != null || ColourIndex != SaXlColourIndex.NotSpecified) return true;
if ((Bold ?? false) || (Strikethrough ?? false) || (Superscript ?? false) || (Subscript ?? false) || (Outline ?? false) || (Shadow ?? false) || (Underline != null)) return true;
return false;
}
}
//=======================================================================
public class SaMsExcelItemAttr : SaMsExcelFontAttr
/// <summary>
/// Style attributes.
/// </summary>
public class SaMsExcelStyleAttr
{
// Item attributes.
public SaMsExcelFontAttr FontAttr { get; } = new SaMsExcelFontAttr();
// Attributes that are changed from their default (generally null) are set against the specified range.
/// <summary>Cell data format. "@"=Text etc.</summary>
public String NumberFormat { get; set; } = String.Empty;
public String DataFormat { get; set; } = String.Empty;
/// <summary>Cell horizontal alignment. XlHAlign.xlHAlignLeft, xlHAlignCenter, xlHAlignRight etc.</summary>
public short? HorizontalAlignment { get; set; } = null;
/// <summary>Cell indentation. Tabbed - left, right or distributed alignment [0 to 6]</summary>
@@ -180,16 +222,16 @@ namespace Sarand.Net.Standard.Proc.Excel
public bool? WrapText { get; set; } = null;
/// <summary>Whether cells are merged.</summary>
public bool? MergeCells { get; set; } = null;
/// <summary>Font colour index, ref. XlColorIndex. Black = 1 etc.</summary>
public SaXlColourIndex InteriorColourIndex { get; set; } = SaXlColourIndex.NotSpecified;
/// <summary>Cell RGB colour value, ref. XlRgbColor. Overrides colour index if changed from default value.</summary>
public int? InteriorColour { get; set; } = null;
/// <summary>Cell pattern, ref. XlPattern. xlSolid etc.</summary>
/// <summary>Font pattern foreground colour index, ref. XlColorIndex. Black = 1 etc.</summary>
public SaXlColourIndex ForegroundColourIndex { get; set; } = SaXlColourIndex.NotSpecified;
/// <summary>Cell pattern foreground RGB colour value, ref. XlRgbColor. Overrides colour index if changed from default value.</summary>
public int? ForegroundColourRGB { get; set; } = null;
/// <summary>Cell pattern, ref. XlPattern. xlSolid etc. NB Defaults to Solid if foreground colour specified.</summary>
public SaXlPattern InteriorPattern { get; set; } = SaXlPattern.NotSpecified;
/// <summary>Cell pattern colour index, ref. XlColorIndex. xlAutomatic etc.</summary>
public SaXlColourIndex InteriorPatternColourIndex { get; set; } = SaXlColourIndex.NotSpecified;
/// <summary>Cell pattern RBG Colour value, ref. XlRgbColor. Overrides colour index if changed from default value.</summary>
public int? InteriorPatternColour { get; set; } = null;
/// <summary>Cell pattern background colour index, ref. XlColorIndex. xlAutomatic etc.</summary>
public SaXlColourIndex BackgroundColourIndex { get; set; } = SaXlColourIndex.NotSpecified;
/// <summary>Cell pattern background RBG Colour value, ref. XlRgbColor. Overrides colour index if changed from default value.</summary>
public int? BackgroundPatternColour { get; set; } = null;
// Borders.
public SaMsExcelBorderAttr BorderLeft { get; } = new SaMsExcelBorderAttr(XlBordersIndex.xlEdgeLeft);
public SaMsExcelBorderAttr BorderTop { get; } = new SaMsExcelBorderAttr(XlBordersIndex.xlEdgeTop);
@@ -201,12 +243,7 @@ namespace Sarand.Net.Standard.Proc.Excel
{
get
{
List<SaMsExcelBorderAttr> borders = new List<SaMsExcelBorderAttr>();
borders.Add(BorderLeft);
borders.Add(BorderTop);
borders.Add(BorderRight);
borders.Add(BorderBottom);
return borders;
return new List<SaMsExcelBorderAttr> { BorderLeft, BorderTop, BorderRight, BorderBottom };
}
}
}
@@ -215,9 +252,12 @@ namespace Sarand.Net.Standard.Proc.Excel
{
//-------------------------------------------------------------------
// Definitions.
public static int FontSizeMin { get; } = 4;
public static int FontSizeMax { get; } = 48;
public static double FontHeightInPointsMin { get; } = 4;
public static double FontHeightInPointsMax { get; } = 48;
public static int NullColour { get; } = 0x4a4d4120; /* AFX_RFX_LONG_PSEUDO_NULL */
public const String Msg_NotSupported = "Not Supported";
public const String Msg_WorkbookNotOpen = "Workbook is not open";
public const String Msg_WorksheetNotOpen = "Worksheet is not open";
//-------------------------------------------------------------------
// Data members.
@@ -235,37 +275,55 @@ namespace Sarand.Net.Standard.Proc.Excel
}
//-------------------------------------------------------------------
// W o r k b o o k
//-------------------------------------------------------------------
// Workbook.
public abstract bool IsWorkbookValid();
public abstract bool CreateWorkbook();
public abstract bool OpenWorkbook(String filePath);
/// <summary>Cleanse workbook - remove unreferenced styles etc.</summary>
public abstract bool CleanseWorkbook();
public abstract bool SaveDocument(String filePath, int fileFormat = (int)SaXlFileFormat.Default /* Default: XlFileFormat.xlOpenXMLWorkbook */, bool bAutomaticallyOverwrite = false);
public abstract bool CloseWorkbook();
public abstract byte[] GetDocumentData();
// Default style.
public abstract void ApplyDefaultStyle(SaMsExcelStyleAttr attr);
//-------------------------------------------------------------------
// W o r k s h e e t
//-------------------------------------------------------------------
/// <summary>Is the current worksheet valid.</summary>
public abstract bool IsWorksheetValid();
// Worksheets.
/// <summary>Number of worksheets in the workbook.</summary>
public abstract uint WorksheetCount { get; }
/// <summary>Set the worksheets in the workbook - sheets are added or removed to match the value.</summary>
public abstract bool SetWorksheetCount(int worksheetCount);
/// <summary>Names of worksheets in the workbook.</summary>
public abstract List<String> WorksheetNames { get; }
/// <summary>Add a worksheet to the workbook.</summary>
public abstract bool AddWorksheet(String name);
/// <summary>Remove the nth worksheet - position from 1.</summary>
public abstract bool RemoveWorksheet(uint worksheetPos);
//-------------------------------------------------------------------
// Worksheet.
/// <summary>Open the nth worksheet - position from 1.</summary>
public abstract bool OpenWorksheet(uint worksheetPos);
/// <summary>Open the worksheet with the specified name.</summary>
public abstract bool OpenWorksheet(String name);
/// <summary>Close the current worksheet.</summary>
public abstract bool CloseWorksheet();
/// <summary>Is the current worksheet valid.</summary>
public abstract bool IsWorksheetValid();
/// <summary>Get the position of the current worksheet. 0 = not open.</summary>
public abstract uint WorksheetPos { get; }
/// <summary>Get the name of the current worksheet.</summary>
public abstract String WorksheetName { get; set; }
/// <summary>Set the default attributes for the entire worksheet</summary>
public abstract bool SetWorksheetAttr(SaMsExcelItemAttr attr);
/// <summary>Close the current worksheet.</summary>
public abstract bool CloseWorksheet();
public abstract bool SetWorksheetAttr(SaMsExcelStyleAttr attr);
// Worksheet Page Setup.
/// <summary>Configure the Page Setup properties.</summary>
public abstract bool SetPageSetup(SaMsExcelPageSetup_Config pageSetupConfig);
@@ -273,110 +331,175 @@ namespace Sarand.Net.Standard.Proc.Excel
public abstract bool SetPageBreak(uint colPos, uint rowPos);
//-------------------------------------------------------------------
// C o l u m n s
//-------------------------------------------------------------------
public abstract uint GetActiveColPos();
// Columns.
public abstract uint ActiveColPos { get; }
public abstract double GetColWidth(uint colPos, SaExcelLogicalUnit unit = SaExcelLogicalUnit.Point);
public abstract bool SetColWidth(uint colPos, double fWidth, SaExcelLogicalUnit unit = SaExcelLogicalUnit.Point);
//-------------------------------------------------------------------
// R o w s
//-------------------------------------------------------------------
public abstract uint GetActiveRowPos();
public abstract List<DataValue> GetRowDataValues(uint rowPos, int maxColumns = 0);
// Rows.
public abstract uint FirstRowPos { get; }
public abstract uint LastRowPos { get; }
public abstract uint ActiveRowPos { get; }
public abstract List<DataValue> GetRowValues(uint rowPos, int maxColumns = 0);
public abstract double GetRowHeight(uint rowPos, SaExcelLogicalUnit unit = SaExcelLogicalUnit.Point);
public abstract bool SetRowHeight(uint rowPos, double fHeight, SaExcelLogicalUnit unit = SaExcelLogicalUnit.Point);
//-------------------------------------------------------------------
// C e l l s
//-------------------------------------------------------------------
// Cells.
public abstract void SetActiveCell(uint colPos, uint rowPos);
public abstract String GetCellFormula(uint colPos, uint rowPos);
public abstract DataValue GetCellDataValue(uint colPos, uint rowPos);
public abstract bool SetCellFormula(uint colPos, uint rowPos, String value);
public abstract bool SetCellFormula(uint colPos, uint rowPos, String value, SaMsExcelItemAttr attr);
public abstract bool SetRowFormulas(uint colStart, uint row, List<Object> values);
public abstract bool SetRangeFormulas(SaMsExcelRange range, List<Object> values);
public abstract String GetCellText(uint colPos, uint rowPos, bool trimWhitespace = true);
public abstract DataValue GetCellValue(uint colPos, uint rowPos);
public abstract bool SetCellFormula(uint colPos, uint rowPos, String value, SaMsExcelStyleAttr attr = null);
public abstract bool SetCellValue(uint colPos, uint rowPos, DataValue value, SaMsExcelStyleAttr attr = null);
/// <summary>Set cell formulas across a row - override if more efficient method available.</summary>
public virtual bool SetRowFormulas(uint colPosStart, uint rowPos, List<String> values)
{
for (uint colPos = Math.Max(1, colPosStart); colPos <= values.Count; colPos++)
SetCellFormula(colPos, rowPos, values[(int)(colPos - 1)]);
return !HasErrorState();
}
/// <summary>Set cell values across a row - override if more efficient method available.</summary>
public virtual bool SetRowValues(uint colPosStart, uint rowPos, List<DataValue> values)
{
for (uint colPos = Math.Max(1, colPosStart); colPos <= values.Count; colPos++)
SetCellValue(colPos, rowPos, values[(int)(colPos - 1)]);
return !HasErrorState();
}
/// <summary>
/// Set cell formulas across a range of cells - override if more efficient logic available.
/// <para>- Values will wrap if more cells to fill than values.</para>
public virtual bool SetRangeFormulas(SaMsExcelRange range, List<String> values)
{
if (values.IsEmpty()) return SetErrorState(SysUtil.Fn + " No values supplied");
int valueIdx = 0;
for (uint colPos = Math.Max(1, range.ColFromPos); colPos <= range.ColToPos; colPos++)
{
for (uint rowPos = Math.Max(1, range.RowFromPos); rowPos <= range.RowToPos; rowPos++)
{
// Wrap values if more cells to fill.
if (valueIdx >= values.Count)
valueIdx = 0;
SetCellFormula(colPos, rowPos, values[valueIdx++]);
}
}
return !HasErrorState();
}
/// <summary>
/// Set cell values across a range of cells - override if more efficient logic available.
/// <para>- Values will wrap if more cells to fill than values.</para>
public virtual bool SetRangeValues(SaMsExcelRange range, List<DataValue> values)
{
if (values.IsEmpty()) return SetErrorState(SysUtil.Fn + " No values supplied");
int valueIdx = 0;
for (uint colPos = Math.Max(1, range.ColFromPos); colPos <= range.ColToPos; colPos++)
{
for (uint rowPos = Math.Max(1, range.RowFromPos); rowPos <= range.RowToPos; rowPos++)
{
// Wrap values if more cells to fill.
if (valueIdx >= values.Count)
valueIdx = 0;
SetCellValue(colPos, rowPos, values[valueIdx++]);
}
}
return !HasErrorState();
}
//-------------------------------------------------------------------
// Populate headings.
public bool SetColumnHeadings(List<ColumnDfn> columns, SaMsExcelColumnHeading_Config config)
public bool SetColumnHeadings(List<ColumnDfn> columns, SaMsExcelColumnHeading_Config headingConfig)
{
ClearErrorState();
double columnWidthPixelsPerCm = Math.Min(100.0, Math.Max(10.0, config.ColumnWidthPixelsPerCm));
uint firstHeadingRow = (uint)Math.Max(1, config.FirstHeadingRow);
double columnWidthPixelsPerCm = Math.Min(100.0, Math.Max(10.0, headingConfig.ColumnWidthPixelsPerCm));
uint firstHeadingRowPos = (uint)Math.Max(1, headingConfig.FirstHeadingRowPos);
// Assume only a single header row.
headingConfig.FirstDataRowPos = firstHeadingRowPos + 1;
try
{
// Populate default heading cell attributes.
SaMsExcelItemAttr attrHdrDefault = new SaMsExcelItemAttr();
attrHdrDefault.Bold = config.HeadingTextBold;
attrHdrDefault.FontSize = (short)Math.Min(80, Math.Max(2, (int)config.HeadingFontSize));
attrHdrDefault.InteriorColourIndex = config.InteriorColourIndex;
if (config.InteriorColour != null)
attrHdrDefault.InteriorColour = config.InteriorColour;
if (config.BorderWeight != SaXlBorderWeight.NotSpecified)
SaMsExcelStyleAttr attrHdrDefault = new SaMsExcelStyleAttr();
attrHdrDefault.FontAttr.CopyFrom(headingConfig.FontAttr);
attrHdrDefault.WrapText = headingConfig.HeadingTextWrap ? true : null;
attrHdrDefault.VerticalAlignment = headingConfig.VerticalAlignment;
attrHdrDefault.ForegroundColourIndex = headingConfig.ForegroundColourIndex;
attrHdrDefault.BackgroundColourIndex = headingConfig.BackgroundColourIndex;
if (headingConfig.ForegroundColourRGB != null)
attrHdrDefault.ForegroundColourRGB = headingConfig.ForegroundColourRGB;
if (headingConfig.BorderWeight != SaXlBorderWeight.NotSpecified)
{
attrHdrDefault.BorderLeft.Weight = config.BorderWeight;
attrHdrDefault.BorderTop.Weight = config.BorderWeight;
attrHdrDefault.BorderRight.Weight = config.BorderWeight;
attrHdrDefault.BorderBottom.Weight = config.BorderWeight;
attrHdrDefault.BorderInsideVertical.Weight = config.BorderWeight;
attrHdrDefault.BorderLeft.Weight = headingConfig.BorderWeight;
attrHdrDefault.BorderTop.Weight = headingConfig.BorderWeight;
attrHdrDefault.BorderRight.Weight = headingConfig.BorderWeight;
attrHdrDefault.BorderBottom.Weight = headingConfig.BorderWeight;
}
SaMsExcelRange rangeHeadings = new SaMsExcelRange(config.FirstHeadingColumn, firstHeadingRow, (uint)(config.FirstHeadingColumn + columns.Count - 1), firstHeadingRow);
SaMsExcelRange rangeHeadings = new SaMsExcelRange(headingConfig.FirstHeadingColPos, firstHeadingRowPos, (uint)(headingConfig.FirstHeadingColPos + columns.Count - 1), firstHeadingRowPos);
SetRangeAttr(rangeHeadings, attrHdrDefault);
// Set default column attributes.
bool defaultColumnAttributesPopulated = false;
SaMsExcelItemAttr attrColDefault = new SaMsExcelItemAttr();
if (config.SetColumnAlignment)
SaMsExcelStyleAttr attrColDefault = new SaMsExcelStyleAttr();
if (headingConfig.SetColumnAlignment)
{
attrColDefault.HorizontalAlignment = (short)XlHAlign.xlHAlignLeft;
defaultColumnAttributesPopulated = true;
}
if (config.SetColumnDataTypeFormat)
if (headingConfig.SetColumnDataTypeFormat)
{
attrColDefault.NumberFormat = "@"; // '@' = 'Text' format.
attrColDefault.DataFormat = "@"; // '@' = 'Text' format.
defaultColumnAttributesPopulated = true;
}
if (defaultColumnAttributesPopulated)
{
SaMsExcelRange rangeColumns = new SaMsExcelRange(config.FirstHeadingColumn, 0, (uint)(config.FirstHeadingColumn + columns.Count - 1), 0);
SaMsExcelRange rangeColumns = new SaMsExcelRange(headingConfig.FirstHeadingColPos, 0, (uint)(headingConfig.FirstHeadingColPos + columns.Count - 1), 0);
SetRangeAttr(rangeColumns, attrColDefault);
}
// Populate column headings and specific styles.
List<Object> values = new List<Object>();
// Populate column styling and headings.
List<DataValue> columnHeadings = new List<DataValue>();
for (int columnIdx = 0; columnIdx < columns.Count; columnIdx++)
{
ColumnDfn column = columns[columnIdx];
uint col = (uint)(Math.Max(1, config.FirstHeadingColumn) + columnIdx);
SaMsExcelRange range = new SaMsExcelRange(col, firstHeadingRow);
uint colPos = (uint)(Math.Max(1, headingConfig.FirstHeadingColPos) + columnIdx);
SaMsExcelRange range = new SaMsExcelRange(colPos, firstHeadingRowPos);
// Specific heading cell attributes - none supported as yet.
// Specific heading cell attributes.
bool headingCellHasSpecificAttr = false;
SaMsExcelItemAttr attrHdr = new SaMsExcelItemAttr();
SaMsExcelStyleAttr attrHdr = new SaMsExcelStyleAttr();
if (headingCellHasSpecificAttr)
SetRangeAttr(range, attrHdr);
// Column width and caption:
if (config.SetColumnWidths) SetColWidth(col, column.Width / columnWidthPixelsPerCm, SaExcelLogicalUnit.Cm);
values.Add(column.Caption);
if (headingConfig.SetColumnWidths) SetColWidth(colPos, column.Width * 1.5 / columnWidthPixelsPerCm, SaExcelLogicalUnit.Cm);
columnHeadings.Add(column.Caption);
// Column attributes:
bool columnHasSpecificAttributes = false;
SaMsExcelItemAttr attrCol = new SaMsExcelItemAttr();
if (config.SetColumnAlignment && column.Alignment != ColumnAlignment.Left && column.Alignment != ColumnAlignment.Default)
bool columnHasSpecificStyle = false;
SaMsExcelStyleAttr attrCol = new SaMsExcelStyleAttr();
if (headingConfig.SetColumnAlignment && column.Alignment != ColumnAlignment.Left && column.Alignment != ColumnAlignment.Default)
{
columnHasSpecificAttributes = true;
columnHasSpecificStyle = true;
switch (column.Alignment)
{
case ColumnAlignment.Center: attrCol.HorizontalAlignment = (short)XlHAlign.xlHAlignCenter; break;
case ColumnAlignment.Right: attrCol.HorizontalAlignment = (short)XlHAlign.xlHAlignRight; break;
}
}
if (config.SetColumnDataTypeFormat && column.DataType != DataValue.DataType.String)
if (column.WrapText)
{
columnHasSpecificAttributes = true;
columnHasSpecificStyle = true;
attrCol.WrapText = true;
}
if (headingConfig.SetColumnDataTypeFormat && column.DataType != DataValue.DataType.String)
{
columnHasSpecificStyle = true;
if (column.DataType == DataValue.DataType.Long || column.DataType == DataValue.DataType.Double || column.DataType == DataValue.DataType.Decimal)
{
// Numeric format: "#,##0.00"
@@ -388,63 +511,66 @@ namespace Sarand.Net.Standard.Proc.Excel
}
if ((column.DataType == DataValue.DataType.Double || column.DataType == DataValue.DataType.Decimal) && column.NumDecimals > 0)
numberFormat += "." + "0".PadRight(column.NumDecimals, '0');
attrCol.NumberFormat = numberFormat + ";[Red]-" + numberFormat;
attrCol.DataFormat = numberFormat + ";[Red]-" + numberFormat;
}
else if (column.DataType == DataValue.DataType.Date) attrCol.NumberFormat = config.CellFormatDate;
else if (column.DataType == DataValue.DataType.Time) attrCol.NumberFormat = config.CellFormatTime;
else if (column.DataType == DataValue.DataType.DateTime) attrCol.NumberFormat = config.CellFormatDate + config.CellFormatDateTimeDelim + config.CellFormatTime;
else if (column.DataType == DataValue.DataType.Date) attrCol.DataFormat = headingConfig.CellFormatDate;
else if (column.DataType == DataValue.DataType.Time) attrCol.DataFormat = headingConfig.CellFormatTime;
else if (column.DataType == DataValue.DataType.DateTime) attrCol.DataFormat = headingConfig.CellFormatDate + headingConfig.CellFormatDateTimeDelim + headingConfig.CellFormatTime;
}
if (columnHasSpecificAttributes)
SetRangeAttr(new SaMsExcelRange(col, 0), attrCol);
if (columnHasSpecificStyle)
SetRangeAttr(new SaMsExcelRange(colPos, 0), attrCol);
// Freeze the window below if a colmn has been specified:
if (config.FreezeColumn > 0) FreezePanes(config.FreezeColumn, firstHeadingRow + 1);
if (headingConfig.FreezeColPos > 0) FreezePanes(headingConfig.FreezeColPos, firstHeadingRowPos + 1);
}
// Populate header captions.
SetRowFormulas(config.FirstHeadingColumn, firstHeadingRow, values);
// Set header row to wrap text:
if (config.HeadingTextWrap)
{
SaMsExcelItemAttr attrRow = new SaMsExcelItemAttr();
attrRow.WrapText = true;
SetRangeAttr(new SaMsExcelRange(0, firstHeadingRow), attrRow);
// Auto fit the header row (set height to fit text):
AutoFit(new SaMsExcelRange(0, firstHeadingRow));
}
SetRowValues(headingConfig.FirstHeadingColPos, firstHeadingRowPos, columnHeadings);
// Auto fit header row if text is wrapped:
if (headingConfig.HeadingTextWrap)
AutoFitRows(rangeHeadings);
}
catch (Exception exc) { HandleException("SetColumnHeadings", exc); }
catch (Exception exc) { HandleException(SysUtil.Fn, exc); }
return !HasErrorState();
}
//-------------------------------------------------------------------
// Cell attributes.
public abstract bool SetRangeAttr(SaMsExcelRange range, SaMsExcelItemAttr attr);
public abstract bool SetRangeAttr(SaMsExcelRange range, SaMsExcelStyleAttr attr);
//-------------------------------------------------------------------
// Add image to sheet.
public abstract bool InsertImage(SaMsExcelImage_Config imageConfig);
//-------------------------------------------------------------------
/// <summary>Freeze sheet at specified cell.</summary>
public abstract bool FreezePanes(uint colPos, uint rowPos);
//-------------------------------------------------------------------
public abstract bool AutoFit(SaMsExcelRange range);
/// <summary>Auto-fit row heights to contents.</summary>
public abstract bool AutoFitRows(SaMsExcelRange range);
//-------------------------------------------------------------------
/// <summary>Select range of cells.</summary>
public abstract bool SelectRange(SaMsExcelRange range);
//-------------------------------------------------------------------
// Utilities.
/// <summary>
/// Convert cell range to Id.
/// <para>- Not fixed: "A9:AB34"</para>
/// <para>- Fixed cols: "$A9:$AB34"</para>
/// <para>- Fixed rows: "A$9:AB$34"</para>
/// <para>- Fixed: "$A$9:$AB$34"</para>
/// </summary>
public static String GetRangeId(SaMsExcelRange range, bool fixedCols = false, bool fixedRows = false)
{
// Not fixed: "A9:AB34"
// Fixed cols: "$A9:$AB34"
// Fixed rows: "A$9:AB$34"
// Fixed: "$A$9:$AB$34"
return (fixedCols ? "$" : "") + GetColumnPrefix(range.ColFrom) + (fixedRows ? "$" : "") + GetRowSuffix(range.RowFrom) + ":" + (fixedCols ? "$" : "") + GetColumnPrefix(range.ColTo) + (fixedRows ? "$" : "") + GetRowSuffix(range.RowTo);
return GetColumnIdPrefix(range.ColFromPos, fixedCols) + GetRowIdSuffix(range.RowFromPos, fixedRows) + ":" + GetColumnIdPrefix(range.ColToPos, fixedCols) + GetRowIdSuffix(range.RowToPos, fixedRows);
}
public static String GetColumnPrefix(uint colPos)
/// <summary>
/// Convert column position to Id prefix. 1=A,2=B,3=C...26=Z,27=AA,28=AB etc.
/// <para>- Fixed prefixes with '$'.</para>
/// </summary>
public static String GetColumnIdPrefix(uint colPos, bool fixedCol = false)
{
// 1=A,2=B,3=C...26=Z,27=AA,28=AB etc
uint dividend = colPos;
string columnName = String.Empty;
uint modulo = 0;
@@ -454,35 +580,51 @@ namespace Sarand.Net.Standard.Proc.Excel
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (uint)((dividend - modulo) / 26);
}
return columnName;
return (fixedCol ? "$" : "") + columnName;
}
public static int GetIndexForCol(String column)
/// <summary>Convert column Id to position. A=1,B=2,C=3...Z=26,AA=27 etc.</summary>
public static int GetPosForColId(String colId)
{
// A=1,B=2,C=3...Z=26,AA=27 etc
int col = (column[0] - 'A');
if (column.Length > 1)
col = (column[1] * 26) + column[0];
colId = StringUtil.TrimWhitespace(StringUtil.OnBlank(colId)).ToUpper();
if (!colId.Matches(new Regex("[A-Z]+")))
{
SaLogger.Warn(SysUtil.Fn + " Invalid column Id supplied: '" + colId + "'");
return -1;
}
int col = (colId[0] - 'A');
if (colId.Length > 1)
col = ((colId[1] - 'A') * 26) + (colId[0] - 'A');
return col;
}
/// <summary>Column Id - To reference entire column: A:A,B:A,C:A...Z:Z,AA:AA etc.</summary>
public static String GetColumnId(uint colPos)
{
// To reference entire column: A:A,B:A,C:A...Z:Z,AA:AA etc
return GetColumnPrefix(colPos) + ":" + GetColumnPrefix(colPos);
return GetColumnIdPrefix(colPos) + ":" + GetColumnIdPrefix(colPos);
}
public static String GetRowSuffix(uint rowPos)
/// <summary>
/// Convert row pos to id suffix. 1=1,2=2,3=3...26=26,27=27,28=28 etc.
/// <para>- Fixed prefixes with '$'.</para>
/// </summary>
public static String GetRowIdSuffix(uint rowPos, bool fixedRow = false)
{
// 1,2,3...26,27,28 etc
return (rowPos > 0 ? rowPos.ToString() : "");
return (rowPos > 0 ? (fixedRow ? "$" : "") + rowPos.ToString() : "");
}
/// <summary>Row id - To reference entire row: 1:1,2:2,3:3 etc.</summary>
public static String GetRowId(uint rowPos)
{
// To reference entire row: 1:1,2:2,3:3 etc
return GetRowSuffix(rowPos) + ":" + GetRowSuffix(rowPos);
return GetRowIdSuffix(rowPos) + ":" + GetRowIdSuffix(rowPos);
}
/// <summary>Convert cell by column and row positions to Id.</summary>
public static String GetCellId(uint colPos, uint rowPos)
{
return GetColumnPrefix(colPos) + GetRowSuffix(rowPos);
return GetColumnIdPrefix(colPos) + GetRowIdSuffix(rowPos);
}
public static DateTime ExtractDate(String value)
{
DateTime date = DateTime.MinValue;
@@ -502,7 +644,7 @@ namespace Sarand.Net.Standard.Proc.Excel
//-------------------------------------------------------------------
public static double PointsPerInch { get; } = 72;
public static double PixelsPerInch { get; } = 96;
public static double CmsPerInch { get; } = 2.54f;
public static double CmsPerInch { get; } = 2.54;
public double ConvertLength(double fLength, SaExcelLogicalUnit eUnitFrom, SaExcelLogicalUnit eUnitTo, bool bVertical)
{
// Convert length to points:
@@ -559,7 +701,7 @@ namespace Sarand.Net.Standard.Proc.Excel
//-------------------------------------------------------------------
protected void HandleException(String fn, Exception exc)
{
SaLogger.Error(GetType().Name + "." + fn + " " + ExceptionUtil.GetLogMessage(exc));
SaLogger.Error(fn + " " + ExceptionUtil.GetLogMessage(exc));
SetErrorState("Problems were encountered interfacing to Excel - " + ExceptionUtil.GetErrorStateMessage(exc));
}