diff --git a/ClosedXML.sln b/ClosedXML.sln index b58a074..cd1cd87 100644 --- a/ClosedXML.sln +++ b/ClosedXML.sln @@ -1,9 +1,9 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25420.1 +# Visual Studio 15 +VisualStudioVersion = 15.0.26730.3 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClosedXML_Sandbox", "ClosedXML_Sandbox\ClosedXML_Sandbox.csproj", "{38B882F0-E6F2-45C5-9BE9-CDC27FBEB4AB}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClosedXML_Sandbox", "ClosedXML_Sandbox\ClosedXML_Sandbox.csproj", "{38B882F0-E6F2-45C5-9BE9-CDC27FBEB4AB}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{5C94E22C-85AA-48FD-B082-CF929FFC6C31}" ProjectSection(SolutionItems) = preProject @@ -11,11 +11,11 @@ ClosedXML.vsmdi = ClosedXML.vsmdi EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClosedXML_Examples", "ClosedXML_Examples\ClosedXML_Examples.csproj", "{03A518D0-1CB7-488E-861C-C4E782B27A46}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClosedXML_Examples", "ClosedXML_Examples\ClosedXML_Examples.csproj", "{03A518D0-1CB7-488E-861C-C4E782B27A46}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClosedXML", "ClosedXML\ClosedXML.csproj", "{BD5E6BFE-E837-4A35-BCA9-39667D873A20}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClosedXML", "ClosedXML\ClosedXML.csproj", "{BD5E6BFE-E837-4A35-BCA9-39667D873A20}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClosedXML_Tests", "ClosedXML_Tests\ClosedXML_Tests.csproj", "{09B066ED-E4A7-4545-A1A4-FF03DD524BDF}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClosedXML_Tests", "ClosedXML_Tests\ClosedXML_Tests.csproj", "{09B066ED-E4A7-4545-A1A4-FF03DD524BDF}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".github", ".github", "{073CFB1C-43DC-4ADC-9D12-BB8D7B10C099}" ProjectSection(SolutionItems) = preProject @@ -49,6 +49,9 @@ GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {2E35B7D8-9690-408F-B52A-F4FC485A6B09} + EndGlobalSection GlobalSection(TestCaseManagementSettings) = postSolution CategoryFile = ClosedXML.vsmdi EndGlobalSection diff --git a/ClosedXML/Attributes/XLColumnAttribute.cs b/ClosedXML/Attributes/XLColumnAttribute.cs index 526dcb0..a86a1be 100644 --- a/ClosedXML/Attributes/XLColumnAttribute.cs +++ b/ClosedXML/Attributes/XLColumnAttribute.cs @@ -1,8 +1,7 @@ +using ClosedXML.Excel; using System; using System.Linq; using System.Reflection; -using ClosedXML; -using ClosedXML.Excel; namespace ClosedXML.Attributes { @@ -23,7 +22,7 @@ { var attribute = GetXLColumnAttribute(mi); if (attribute == null) return null; - return String.IsNullOrWhiteSpace(attribute.Header) ? null : attribute.Header; + return XLHelper.IsNullOrWhiteSpace(attribute.Header) ? null : attribute.Header; } internal static Int32 GetOrder(MemberInfo mi) diff --git a/ClosedXML/ClosedXML.csproj b/ClosedXML/ClosedXML.csproj index 3125799..8f3cc12 100644 --- a/ClosedXML/ClosedXML.csproj +++ b/ClosedXML/ClosedXML.csproj @@ -1,385 +1,53 @@ - - + + - Debug - AnyCPU - 8.0.30703 - 2.0 - {BD5E6BFE-E837-4A35-BCA9-39667D873A20} - Library - Properties - ClosedXML - ClosedXML - v4.0 - 512 - ..\ - true - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - 1591 - false - 6 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - bin\Release\ClosedXML.xml - 1591 - false - 6 - - + netstandard2.0;net40;net46 + 0.9 + Manuel de Leon, Amir Ghezelbash, Francois Botha + + + ClosedXML makes it easier for developers to create Excel 2007+ (.xlsx, .xlsm, etc) files. It provides a nice object oriented way to manipulate the files (similar to VBA) without dealing with the hassles of XML Documents. It can be used by any .NET language like C# and VisualBasic.NET. + MIT + https://github.com/ClosedXML/ClosedXML/blob/master/LICENSE + https://github.com/ClosedXML/ClosedXML + https://github.com/ClosedXML/ClosedXML true - - ClosedXML.snk + $(NoWarn);NU1605;CS1591 + true - - - ..\packages\DocumentFormat.OpenXml.2.7.2\lib\net40\DocumentFormat.OpenXml.dll - True - - - ..\packages\ExcelNumberFormat.1.0.3\lib\net20\ExcelNumberFormat.dll - True - - - ..\packages\FastMember.Signed.1.3.0\lib\net40\FastMember.Signed.dll - True - + + + $(DefineConstants);_NETSTANDARD_;_NETSTANDARD2_0_ + + + + $(DefineConstants);_NETFRAMEWORK_;_NET40_ + + + + $(DefineConstants);_NETFRAMEWORK_;_NET46_ + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - .editorconfig - - - + - - - \ No newline at end of file + + + + + + + diff --git a/ClosedXML/Excel/CalcEngine/XLCalcEngine.cs b/ClosedXML/Excel/CalcEngine/XLCalcEngine.cs index da2f83b..86155cb 100644 --- a/ClosedXML/Excel/CalcEngine/XLCalcEngine.cs +++ b/ClosedXML/Excel/CalcEngine/XLCalcEngine.cs @@ -101,7 +101,7 @@ { _evaluating = true; var f = cell.FormulaA1; - if (String.IsNullOrWhiteSpace(f)) + if (XLHelper.IsNullOrWhiteSpace(f)) return cell.Value; else return new XLCalcEngine(cell.Worksheet).Evaluate(f); diff --git a/ClosedXML/Excel/Cells/XLCell.cs b/ClosedXML/Excel/Cells/XLCell.cs index 58afd37..1debabd 100644 --- a/ClosedXML/Excel/Cells/XLCell.cs +++ b/ClosedXML/Excel/Cells/XLCell.cs @@ -353,7 +353,7 @@ return cValue; } else - return cValue; + return cValue; } /// @@ -366,7 +366,7 @@ get { var fA1 = FormulaA1; - if (!String.IsNullOrWhiteSpace(fA1)) + if (!XLHelper.IsNullOrWhiteSpace(fA1)) { if (IsEvaluating) throw new InvalidOperationException("Circular Reference"); @@ -524,7 +524,7 @@ if (!hasTitles) { var fieldName = XLColumnAttribute.GetHeader(itemType); - if (String.IsNullOrWhiteSpace(fieldName)) + if (XLHelper.IsNullOrWhiteSpace(fieldName)) fieldName = itemType.Name; _worksheet.SetValue(fieldName, fRo, co); @@ -602,7 +602,7 @@ if (!hasTitles) { foreach (var fieldName in from DataColumn column in row.Table.Columns - select String.IsNullOrWhiteSpace(column.Caption) + select XLHelper.IsNullOrWhiteSpace(column.Caption) ? column.ColumnName : column.Caption) { @@ -655,7 +655,7 @@ if (!(mi is IEnumerable)) { var fieldName = XLColumnAttribute.GetHeader(mi); - if (String.IsNullOrWhiteSpace(fieldName)) + if (XLHelper.IsNullOrWhiteSpace(fieldName)) fieldName = mi.Name; _worksheet.SetValue(fieldName, fRo, co); @@ -1083,9 +1083,9 @@ { get { - if (String.IsNullOrWhiteSpace(_formulaA1)) + if (XLHelper.IsNullOrWhiteSpace(_formulaA1)) { - if (!String.IsNullOrWhiteSpace(_formulaR1C1)) + if (!XLHelper.IsNullOrWhiteSpace(_formulaR1C1)) { _formulaA1 = GetFormulaA1(_formulaR1C1); return FormulaA1; @@ -1105,7 +1105,7 @@ set { - _formulaA1 = String.IsNullOrWhiteSpace(value) ? null : value; + _formulaA1 = XLHelper.IsNullOrWhiteSpace(value) ? null : value; _formulaR1C1 = null; } @@ -1115,7 +1115,7 @@ { get { - if (String.IsNullOrWhiteSpace(_formulaR1C1)) + if (XLHelper.IsNullOrWhiteSpace(_formulaR1C1)) _formulaR1C1 = GetFormulaR1C1(FormulaA1); return _formulaR1C1; @@ -1123,7 +1123,7 @@ set { - _formulaR1C1 = String.IsNullOrWhiteSpace(value) ? null : value; + _formulaR1C1 = XLHelper.IsNullOrWhiteSpace(value) ? null : value; _formulaA1 = null; } @@ -1763,7 +1763,7 @@ { var style = GetStyleForRead(); return _dataType == XLDataType.Number - && String.IsNullOrWhiteSpace(style.NumberFormat.Format) + && XLHelper.IsNullOrWhiteSpace(style.NumberFormat.Format) && ((style.NumberFormat.NumberFormatId >= 14 && style.NumberFormat.NumberFormatId <= 22) || (style.NumberFormat.NumberFormatId >= 45 @@ -1774,7 +1774,7 @@ { var format = String.Empty; var style = GetStyleForRead(); - if (String.IsNullOrWhiteSpace(style.NumberFormat.Format)) + if (XLHelper.IsNullOrWhiteSpace(style.NumberFormat.Format)) { var formatCodes = XLPredefinedFormat.FormatCodes; if (formatCodes.ContainsKey(style.NumberFormat.NumberFormatId)) @@ -2039,7 +2039,7 @@ private string GetFormula(string strValue, FormulaConversionType conversionType, int rowsToShift, int columnsToShift) { - if (String.IsNullOrWhiteSpace(strValue)) + if (XLHelper.IsNullOrWhiteSpace(strValue)) return String.Empty; var value = ">" + strValue + "<"; @@ -2321,7 +2321,7 @@ internal static String ShiftFormulaRows(String formulaA1, XLWorksheet worksheetInAction, XLRange shiftedRange, int rowsShifted) { - if (String.IsNullOrWhiteSpace(formulaA1)) return String.Empty; + if (XLHelper.IsNullOrWhiteSpace(formulaA1)) return String.Empty; var value = formulaA1; @@ -2470,7 +2470,7 @@ internal static String ShiftFormulaColumns(String formulaA1, XLWorksheet worksheetInAction, XLRange shiftedRange, int columnsShifted) { - if (String.IsNullOrWhiteSpace(formulaA1)) return String.Empty; + if (XLHelper.IsNullOrWhiteSpace(formulaA1)) return String.Empty; var value = formulaA1; @@ -2739,7 +2739,7 @@ #endregion XLCell Right - public Boolean HasFormula { get { return !String.IsNullOrWhiteSpace(FormulaA1); } } + public Boolean HasFormula { get { return !XLHelper.IsNullOrWhiteSpace(FormulaA1); } } public Boolean HasArrayFormula { get { return FormulaA1.StartsWith("{"); } } diff --git a/ClosedXML/Excel/Columns/XLColumn.cs b/ClosedXML/Excel/Columns/XLColumn.cs index cb8aae5..9a94c32 100644 --- a/ClosedXML/Excel/Columns/XLColumn.cs +++ b/ClosedXML/Excel/Columns/XLColumn.cs @@ -297,6 +297,7 @@ public IXLColumn AdjustToContents(Int32 startRow, Int32 endRow, Double minWidth, Double maxWidth) { var fontCache = new Dictionary(); + Double colMaxWidth = minWidth; List autoFilterRows = new List(); diff --git a/ClosedXML/Excel/ConditionalFormats/Save/XLCFColorScaleConverter.cs b/ClosedXML/Excel/ConditionalFormats/Save/XLCFColorScaleConverter.cs index 5fc548c..bddd195 100644 --- a/ClosedXML/Excel/ConditionalFormats/Save/XLCFColorScaleConverter.cs +++ b/ClosedXML/Excel/ConditionalFormats/Save/XLCFColorScaleConverter.cs @@ -1,5 +1,5 @@ -using System; using DocumentFormat.OpenXml.Spreadsheet; +using System; namespace ClosedXML.Excel { diff --git a/ClosedXML/Excel/ConditionalFormats/Save/XLCFDataBarConverter.cs b/ClosedXML/Excel/ConditionalFormats/Save/XLCFDataBarConverter.cs index 29300fa..67b19a0 100644 --- a/ClosedXML/Excel/ConditionalFormats/Save/XLCFDataBarConverter.cs +++ b/ClosedXML/Excel/ConditionalFormats/Save/XLCFDataBarConverter.cs @@ -1,7 +1,7 @@ -using System; -using System.Linq; using ClosedXML.Extensions; using DocumentFormat.OpenXml.Spreadsheet; +using System; +using System.Linq; namespace ClosedXML.Excel { @@ -25,9 +25,11 @@ case XLColorType.Color: color.Rgb = cf.Colors[1].Color.ToHex(); break; + case XLColorType.Theme: color.Theme = System.Convert.ToUInt32(cf.Colors[1].ThemeColor); break; + case XLColorType.Indexed: color.Indexed = System.Convert.ToUInt32(cf.Colors[1].Indexed); break; @@ -37,7 +39,6 @@ dataBar.Append(conditionalFormatValueObject2); dataBar.Append(color); - conditionalFormattingRule.Append(dataBar); if (cf.Colors.Count > 1) diff --git a/ClosedXML/Excel/DataValidation/XLDataValidation.cs b/ClosedXML/Excel/DataValidation/XLDataValidation.cs index 3ee5896..8c189db 100644 --- a/ClosedXML/Excel/DataValidation/XLDataValidation.cs +++ b/ClosedXML/Excel/DataValidation/XLDataValidation.cs @@ -48,9 +48,9 @@ return AllowedValues != XLAllowedValues.AnyValue || (ShowInputMessage && - (!String.IsNullOrWhiteSpace(InputTitle) || !String.IsNullOrWhiteSpace(InputMessage))) + (!XLHelper.IsNullOrWhiteSpace(InputTitle) || !XLHelper.IsNullOrWhiteSpace(InputMessage))) ||(ShowErrorMessage && - (!String.IsNullOrWhiteSpace(ErrorTitle) || !String.IsNullOrWhiteSpace(ErrorMessage))); + (!XLHelper.IsNullOrWhiteSpace(ErrorTitle) || !XLHelper.IsNullOrWhiteSpace(ErrorMessage))); } diff --git a/ClosedXML/Excel/Drawings/PictureEnums.cs b/ClosedXML/Excel/Drawings/PictureEnums.cs index 3d76e73..f00f85b 100644 --- a/ClosedXML/Excel/Drawings/PictureEnums.cs +++ b/ClosedXML/Excel/Drawings/PictureEnums.cs @@ -14,9 +14,9 @@ Tiff = 3, Icon = 4, Pcx = 5, - Jpeg = 6, - Emf = 7, - Wmf = 8 + Jpeg = 6 + //Emf = 7, + //Wmf = 8 } public enum XLPicturePlacement diff --git a/ClosedXML/Excel/Drawings/XLPictures.cs b/ClosedXML/Excel/Drawings/XLPictures.cs index c539d0e..705ccb1 100644 --- a/ClosedXML/Excel/Drawings/XLPictures.cs +++ b/ClosedXML/Excel/Drawings/XLPictures.cs @@ -73,9 +73,9 @@ public IXLPicture Add(string imageFile) { - using (var bitmap = Image.FromFile(imageFile) as Bitmap) + using (var fs = File.Open(imageFile, FileMode.Open)) { - var picture = new XLPicture(_worksheet, bitmap); + var picture = new XLPicture(_worksheet, fs); _pictures.Add(picture); picture.Name = GetNextPictureName(); return picture; diff --git a/ClosedXML/Excel/IXLTheme.cs b/ClosedXML/Excel/IXLTheme.cs index 17e4e57..b506e22 100644 --- a/ClosedXML/Excel/IXLTheme.cs +++ b/ClosedXML/Excel/IXLTheme.cs @@ -1,6 +1,3 @@ -using ClosedXML.Excel; -using System.Drawing; - namespace ClosedXML.Excel { public interface IXLTheme diff --git a/ClosedXML/Excel/Misc/XLFormula.cs b/ClosedXML/Excel/Misc/XLFormula.cs index 8027667..34cea84 100644 --- a/ClosedXML/Excel/Misc/XLFormula.cs +++ b/ClosedXML/Excel/Misc/XLFormula.cs @@ -44,7 +44,7 @@ else { _value = value.Trim(); - IsFormula = !String.IsNullOrWhiteSpace(_value) && _value.TrimStart()[0] == '=' ; + IsFormula = !XLHelper.IsNullOrWhiteSpace(_value) && _value.TrimStart()[0] == '=' ; if (IsFormula) _value = _value.Substring(1); } diff --git a/ClosedXML/Excel/PageSetup/XLHFText.cs b/ClosedXML/Excel/PageSetup/XLHFText.cs index f9530a3..6659cd6 100644 --- a/ClosedXML/Excel/PageSetup/XLHFText.cs +++ b/ClosedXML/Excel/PageSetup/XLHFText.cs @@ -6,11 +6,13 @@ internal class XLHFText { private readonly XLHFItem _hfItem; + public XLHFText(XLRichString richText, XLHFItem hfItem) { RichText = richText; _hfItem = hfItem; } + public XLRichString RichText { get; private set; } public String GetHFText(String prevText) @@ -98,6 +100,5 @@ return sb.ToString(); } - } } diff --git a/ClosedXML/Excel/Ranges/XLRangeBase.cs b/ClosedXML/Excel/Ranges/XLRangeBase.cs index 5c9e661..84948c3 100644 --- a/ClosedXML/Excel/Ranges/XLRangeBase.cs +++ b/ClosedXML/Excel/Ranges/XLRangeBase.cs @@ -1126,7 +1126,7 @@ { foreach (XLWorksheet ws in Worksheet.Workbook.WorksheetsInternal) { - foreach (XLCell cell in ws.Internals.CellsCollection.GetCells(c => !String.IsNullOrWhiteSpace(c.FormulaA1))) + foreach (XLCell cell in ws.Internals.CellsCollection.GetCells(c => !XLHelper.IsNullOrWhiteSpace(c.FormulaA1))) using (var asRange = AsRange()) cell.ShiftFormulaColumns(asRange, numberOfColumns); } @@ -1342,7 +1342,7 @@ using (var asRange = AsRange()) foreach (XLWorksheet ws in Worksheet.Workbook.WorksheetsInternal) { - foreach (XLCell cell in ws.Internals.CellsCollection.GetCells(c => !String.IsNullOrWhiteSpace(c.FormulaA1))) + foreach (XLCell cell in ws.Internals.CellsCollection.GetCells(c => !XLHelper.IsNullOrWhiteSpace(c.FormulaA1))) cell.ShiftFormulaRows(asRange, numberOfRows); } @@ -1503,7 +1503,7 @@ XLCell cell in Worksheet.Workbook.Worksheets.Cast().SelectMany( xlWorksheet => (xlWorksheet).Internals.CellsCollection.GetCells( - c => !String.IsNullOrWhiteSpace(c.FormulaA1)))) + c => !XLHelper.IsNullOrWhiteSpace(c.FormulaA1)))) { if (shiftDeleteCells == XLShiftDeletedCells.ShiftCellsUp) cell.ShiftFormulaRows((XLRange)shiftedRangeFormula, numberOfRows * -1); @@ -1791,7 +1791,7 @@ public IXLRangeBase Sort(String columnsToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true) { SortColumns.Clear(); - if (String.IsNullOrWhiteSpace(columnsToSortBy)) + if (XLHelper.IsNullOrWhiteSpace(columnsToSortBy)) { columnsToSortBy = DefaultSortString(); } diff --git a/ClosedXML/Excel/Rows/XLRow.cs b/ClosedXML/Excel/Rows/XLRow.cs index e7f4cd8..697801e 100644 --- a/ClosedXML/Excel/Rows/XLRow.cs +++ b/ClosedXML/Excel/Rows/XLRow.cs @@ -285,6 +285,7 @@ public IXLRow AdjustToContents(Int32 startColumn, Int32 endColumn, Double minHeight, Double maxHeight) { var fontCache = new Dictionary(); + Double rowMaxHeight = minHeight; foreach (XLCell c in from XLCell c in Row(startColumn, endColumn).CellsUsed() where !c.IsMerged() select c) { diff --git a/ClosedXML/Excel/SaveOptions.cs b/ClosedXML/Excel/SaveOptions.cs index 7dcd9a1..62edb53 100644 --- a/ClosedXML/Excel/SaveOptions.cs +++ b/ClosedXML/Excel/SaveOptions.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace ClosedXML.Excel { @@ -19,6 +15,7 @@ this.EvaluateFormulasBeforeSaving = false; this.GenerateCalculationChain = true; } + public Boolean ValidatePackage; public Boolean EvaluateFormulasBeforeSaving; public Boolean GenerateCalculationChain; diff --git a/ClosedXML/Excel/Style/Colors/XLColor_Internal.cs b/ClosedXML/Excel/Style/Colors/XLColor_Internal.cs index a5aeafc..dcea153 100644 --- a/ClosedXML/Excel/Style/Colors/XLColor_Internal.cs +++ b/ClosedXML/Excel/Style/Colors/XLColor_Internal.cs @@ -65,4 +65,4 @@ _colorType = XLColorType.Theme; } } -} \ No newline at end of file +} diff --git a/ClosedXML/Excel/Style/Colors/XLColor_Public.cs b/ClosedXML/Excel/Style/Colors/XLColor_Public.cs index 4d0d9d3..ce6031a 100644 --- a/ClosedXML/Excel/Style/Colors/XLColor_Public.cs +++ b/ClosedXML/Excel/Style/Colors/XLColor_Public.cs @@ -105,7 +105,7 @@ if (ColorType == XLColorType.Indexed) throw new InvalidOperationException("Cannot extract theme tint from an indexed color."); - return _color.A/255.0; + return _color.A / 255.0; } } @@ -132,11 +132,11 @@ return false; } - #endregion + #endregion IEquatable Members public override bool Equals(object obj) { - return Equals((XLColor) obj); + return Equals((XLColor)obj); } public override int GetHashCode() diff --git a/ClosedXML/Excel/Style/Colors/XLColor_Static.cs b/ClosedXML/Excel/Style/Colors/XLColor_Static.cs index 3c8ec59..efd6b7c 100644 --- a/ClosedXML/Excel/Style/Colors/XLColor_Static.cs +++ b/ClosedXML/Excel/Style/Colors/XLColor_Static.cs @@ -39,10 +39,12 @@ return FromColor(Color.FromArgb(a, r, g, b)); } +#if _NETFRAMEWORK_ public static XLColor FromKnownColor(KnownColor color) { return FromColor(Color.FromKnownColor(color)); } +#endif public static XLColor FromName(String name) { diff --git a/ClosedXML/Excel/Style/IXLFontBase.cs b/ClosedXML/Excel/Style/IXLFontBase.cs index 629cab1..77ac7a1 100644 --- a/ClosedXML/Excel/Style/IXLFontBase.cs +++ b/ClosedXML/Excel/Style/IXLFontBase.cs @@ -2,9 +2,7 @@ namespace ClosedXML.Excel { - - - public interface IXLFontBase + public interface IXLFontBase { Boolean Bold { get; set; } Boolean Italic { get; set; } diff --git a/ClosedXML/Excel/Tables/XLTable.cs b/ClosedXML/Excel/Tables/XLTable.cs index 97f5c5f..d42ddf1 100644 --- a/ClosedXML/Excel/Tables/XLTable.cs +++ b/ClosedXML/Excel/Tables/XLTable.cs @@ -96,7 +96,7 @@ continue; } - if (String.IsNullOrWhiteSpace(name)) + if (XLHelper.IsNullOrWhiteSpace(name)) { name = GetUniqueName("Column", cellPos + 1, true); cell.SetValue(name); @@ -347,7 +347,7 @@ var co = 1; foreach (var c in firstRow.Cells()) { - if (String.IsNullOrWhiteSpace(((XLCell)c).InnerText)) + if (XLHelper.IsNullOrWhiteSpace(((XLCell)c).InnerText)) c.Value = GetUniqueName("Column", co, true); var header = c.GetString(); @@ -393,7 +393,7 @@ { f.UpdateUnderlyingCellFormula(); var c = this.TotalsRow().Cell(f.Index + 1); - if (!String.IsNullOrWhiteSpace(f.TotalsRowLabel)) + if (!XLHelper.IsNullOrWhiteSpace(f.TotalsRowLabel)) { c.DataType = XLDataType.Text; @@ -566,7 +566,7 @@ Int32 co = 1; foreach (IXLCell c in range.Row(1).Cells()) { - if (String.IsNullOrWhiteSpace(((XLCell)c).InnerText)) + if (XLHelper.IsNullOrWhiteSpace(((XLCell)c).InnerText)) c.Value = GetUniqueName("Column", co, true); _uniqueNames.Add(c.GetString()); co++; @@ -619,7 +619,7 @@ Int32 co = 1; foreach (IXLCell c in headersRow.Cells()) { - if (String.IsNullOrWhiteSpace(((XLCell)c).InnerText)) + if (XLHelper.IsNullOrWhiteSpace(((XLCell)c).InnerText)) c.Value = GetUniqueName("Column", co, true); _uniqueNames.Add(c.GetString()); co++; diff --git a/ClosedXML/Excel/XLWorkbook.cs b/ClosedXML/Excel/XLWorkbook.cs index b3eb5ad..3a22085 100644 --- a/ClosedXML/Excel/XLWorkbook.cs +++ b/ClosedXML/Excel/XLWorkbook.cs @@ -53,60 +53,60 @@ { return _defaultStyle ?? (_defaultStyle = new XLStyle(null) + { + Font = new XLFont(null, null) { - Font = new XLFont(null, null) - { - Bold = false, - Italic = false, - Underline = XLFontUnderlineValues.None, - Strikethrough = false, - VerticalAlignment = XLFontVerticalTextAlignmentValues.Baseline, - FontSize = 11, - FontColor = XLColor.FromArgb(0, 0, 0), - FontName = "Calibri", - FontFamilyNumbering = XLFontFamilyNumberingValues.Swiss, - FontCharSet = XLFontCharSet.Default - }, - Fill = new XLFill(null) - { - BackgroundColor = XLColor.FromIndex(64), - PatternType = XLFillPatternValues.None, - PatternColor = XLColor.FromIndex(64) - }, - Border = new XLBorder(null, null) - { - BottomBorder = XLBorderStyleValues.None, - DiagonalBorder = XLBorderStyleValues.None, - DiagonalDown = false, - DiagonalUp = false, - LeftBorder = XLBorderStyleValues.None, - RightBorder = XLBorderStyleValues.None, - TopBorder = XLBorderStyleValues.None, - BottomBorderColor = XLColor.Black, - DiagonalBorderColor = XLColor.Black, - LeftBorderColor = XLColor.Black, - RightBorderColor = XLColor.Black, - TopBorderColor = XLColor.Black - }, - NumberFormat = new XLNumberFormat(null, null) { NumberFormatId = 0 }, - Alignment = new XLAlignment(null) - { - Indent = 0, - Horizontal = XLAlignmentHorizontalValues.General, - JustifyLastLine = false, - ReadingOrder = XLAlignmentReadingOrderValues.ContextDependent, - RelativeIndent = 0, - ShrinkToFit = false, - TextRotation = 0, - Vertical = XLAlignmentVerticalValues.Bottom, - WrapText = false - }, - Protection = new XLProtection(null) - { - Locked = true, - Hidden = false - } - }); + Bold = false, + Italic = false, + Underline = XLFontUnderlineValues.None, + Strikethrough = false, + VerticalAlignment = XLFontVerticalTextAlignmentValues.Baseline, + FontSize = 11, + FontColor = XLColor.FromArgb(0, 0, 0), + FontName = "Calibri", + FontFamilyNumbering = XLFontFamilyNumberingValues.Swiss, + FontCharSet = XLFontCharSet.Default + }, + Fill = new XLFill(null) + { + BackgroundColor = XLColor.FromIndex(64), + PatternType = XLFillPatternValues.None, + PatternColor = XLColor.FromIndex(64) + }, + Border = new XLBorder(null, null) + { + BottomBorder = XLBorderStyleValues.None, + DiagonalBorder = XLBorderStyleValues.None, + DiagonalDown = false, + DiagonalUp = false, + LeftBorder = XLBorderStyleValues.None, + RightBorder = XLBorderStyleValues.None, + TopBorder = XLBorderStyleValues.None, + BottomBorderColor = XLColor.Black, + DiagonalBorderColor = XLColor.Black, + LeftBorderColor = XLColor.Black, + RightBorderColor = XLColor.Black, + TopBorderColor = XLColor.Black + }, + NumberFormat = new XLNumberFormat(null, null) { NumberFormatId = 0 }, + Alignment = new XLAlignment(null) + { + Indent = 0, + Horizontal = XLAlignmentHorizontalValues.General, + JustifyLastLine = false, + ReadingOrder = XLAlignmentReadingOrderValues.ContextDependent, + RelativeIndent = 0, + ShrinkToFit = false, + TextRotation = 0, + Vertical = XLAlignmentVerticalValues.Bottom, + WrapText = false + }, + Protection = new XLProtection(null) + { + Locked = true, + Hidden = false + } + }); } } @@ -513,7 +513,6 @@ { CopyStream(_originalStream, fileStream); CreatePackage(fileStream, false, _spreadsheetDocumentType, options); - fileStream.Close(); } } @@ -606,7 +605,6 @@ using (var fileStream = new FileStream(_originalFile, FileMode.Open, FileAccess.Read)) { CopyStream(fileStream, stream); - fileStream.Close(); } CreatePackage(stream, false, _spreadsheetDocumentType, options); } diff --git a/ClosedXML/Excel/XLWorkbook_Load.cs b/ClosedXML/Excel/XLWorkbook_Load.cs index 8aa12c5..a322ce2 100644 --- a/ClosedXML/Excel/XLWorkbook_Load.cs +++ b/ClosedXML/Excel/XLWorkbook_Load.cs @@ -1,5 +1,3 @@ -#region - using ClosedXML.Extensions; using ClosedXML.Utils; using DocumentFormat.OpenXml; @@ -17,19 +15,13 @@ using Op = DocumentFormat.OpenXml.CustomProperties; using Xdr = DocumentFormat.OpenXml.Drawing.Spreadsheet; -#endregion - namespace ClosedXML.Excel { - #region - using Ap; using Drawings; using Op; using System.Drawing; - #endregion - public partial class XLWorkbook { private readonly Dictionary _colorList = new Dictionary(); @@ -287,7 +279,7 @@ String reference = dTable.Reference.Value; String tableName = dTable?.Name ?? dTable.DisplayName ?? string.Empty; - if (String.IsNullOrWhiteSpace(tableName)) + if (XLHelper.IsNullOrWhiteSpace(tableName)) throw new InvalidDataException("The table name is missing."); var xlTable = ws.Range(reference).CreateTable(tableName, false) as XLTable; @@ -362,7 +354,7 @@ xlTable.AutoFilter.Range = xlTable.Worksheet.Range(xlTable.RangeAddress); } - #endregion + #endregion LoadTables LoadDrawings(worksheetPart, ws); @@ -418,7 +410,7 @@ } } - #endregion + #endregion LoadComments } var workbook = dSpreadsheet.WorkbookPart.Workbook; @@ -489,10 +481,10 @@ { var pt = ws.PivotTables.AddNew(pivotTableDefinition.Name, target, source) as XLPivotTable; - if (!String.IsNullOrWhiteSpace(StringValue.ToString(pivotTableDefinition?.ColumnHeaderCaption ?? String.Empty))) + if (!XLHelper.IsNullOrWhiteSpace(StringValue.ToString(pivotTableDefinition?.ColumnHeaderCaption ?? String.Empty))) pt.SetColumnHeaderCaption(StringValue.ToString(pivotTableDefinition.ColumnHeaderCaption)); - if (!String.IsNullOrWhiteSpace(StringValue.ToString(pivotTableDefinition?.RowHeaderCaption ?? String.Empty))) + if (!XLHelper.IsNullOrWhiteSpace(StringValue.ToString(pivotTableDefinition?.RowHeaderCaption ?? String.Empty))) pt.SetRowHeaderCaption(StringValue.ToString(pivotTableDefinition.RowHeaderCaption)); pt.RelId = worksheetPart.GetIdOfPart(pivotTablePart); @@ -760,7 +752,7 @@ } } - #endregion + #endregion Pivot tables } private static void LoadFieldOptions(PivotField pf, IXLPivotField pivotField) @@ -825,10 +817,12 @@ var imagePart = drawingsPart.GetPartById(imgId); using (var stream = imagePart.GetStream()) + using (var ms = new MemoryStream()) { + stream.CopyTo(ms); var vsdp = GetPropertiesFromAnchor(anchor); - var picture = (ws as XLWorksheet).AddPicture(stream, vsdp.Name, Convert.ToInt32(vsdp.Id.Value)) as XLPicture; + var picture = (ws as XLWorksheet).AddPicture(ms, vsdp.Name, Convert.ToInt32(vsdp.Id.Value)) as XLPicture; picture.RelId = imgId; Xdr.ShapeProperties spPr = anchor.Descendants().First(); @@ -940,7 +934,7 @@ return shape; } - #endregion + #endregion Comment Helpers private String GetTableColumnName(string name) { @@ -1384,7 +1378,7 @@ { if (cell.CellFormula.SharedIndex != null) xlCell.FormulaR1C1 = sharedFormulasR1C1[cell.CellFormula.SharedIndex.Value]; - else if (!String.IsNullOrWhiteSpace(cell.CellFormula.Text)) + else if (!XLHelper.IsNullOrWhiteSpace(cell.CellFormula.Text)) { String formula; if (cell.CellFormula.FormulaType != null && cell.CellFormula.FormulaType == CellFormulaValues.Array) @@ -1429,7 +1423,7 @@ } else if (cell.DataType == CellValues.SharedString) { - if (cell.CellValue != null && !String.IsNullOrWhiteSpace(cell.CellValue.Text)) + if (cell.CellValue != null && !XLHelper.IsNullOrWhiteSpace(cell.CellValue.Text)) { var sharedString = sharedStrings[Int32.Parse(cell.CellValue.Text, XLHelper.NumberStyle, XLHelper.ParseCulture)]; ParseCellValue(sharedString, xlCell); @@ -1441,7 +1435,7 @@ } else if (cell.DataType == CellValues.Date) { - if (cell.CellValue != null && !String.IsNullOrWhiteSpace(cell.CellValue.Text)) + if (cell.CellValue != null && !XLHelper.IsNullOrWhiteSpace(cell.CellValue.Text)) xlCell._cellValue = Double.Parse(cell.CellValue.Text, XLHelper.NumberStyle, XLHelper.ParseCulture).ToInvariantString(); xlCell._dataType = XLDataType.DateTime; } @@ -1453,7 +1447,7 @@ } else if (cell.DataType == CellValues.Number) { - if (cell.CellValue != null && !String.IsNullOrWhiteSpace(cell.CellValue.Text)) + if (cell.CellValue != null && !XLHelper.IsNullOrWhiteSpace(cell.CellValue.Text)) xlCell._cellValue = Double.Parse(cell.CellValue.Text, XLHelper.NumberStyle, XLHelper.ParseCulture).ToInvariantString(); if (s == null) @@ -1471,7 +1465,7 @@ else { var numberFormatId = ((CellFormat)(s.CellFormats).ElementAt(styleIndex)).NumberFormatId; - if (!String.IsNullOrWhiteSpace(cell.CellValue.Text)) + if (!XLHelper.IsNullOrWhiteSpace(cell.CellValue.Text)) xlCell._cellValue = Double.Parse(cell.CellValue.Text, CultureInfo.InvariantCulture).ToInvariantString(); if (s.NumberingFormats != null && @@ -1542,7 +1536,7 @@ LoadFont(pp, xlCell.RichText.Phonetics); } - #endregion + #endregion Load PhoneticProperties #region Load Phonetic Runs @@ -1552,7 +1546,7 @@ (Int32)pr.EndingBaseIndex.Value); } - #endregion + #endregion Load Phonetic Runs } private void LoadNumberFormat(NumberingFormat nfSource, IXLNumberFormat nf) @@ -1793,7 +1787,7 @@ return XLDataType.Text; else { - if (!String.IsNullOrWhiteSpace(numberFormat.Format)) + if (!XLHelper.IsNullOrWhiteSpace(numberFormat.Format)) { var dataType = GetDataTypeFromFormat(numberFormat.Format); return dataType.HasValue ? dataType.Value : XLDataType.Number; @@ -1873,7 +1867,7 @@ { case XLFilterOperator.Equal: if (isText) - condition = o => o.ToString().Equals(xlFilter.Value.ToString(), StringComparison.InvariantCultureIgnoreCase); + condition = o => o.ToString().Equals(xlFilter.Value.ToString(), StringComparison.OrdinalIgnoreCase); else condition = o => (o as IComparable).CompareTo(xlFilter.Value) == 0; break; @@ -1884,7 +1878,7 @@ case XLFilterOperator.LessThan: condition = o => (o as IComparable).CompareTo(xlFilter.Value) < 0; break; case XLFilterOperator.NotEqual: if (isText) - condition = o => !o.ToString().Equals(xlFilter.Value.ToString(), StringComparison.InvariantCultureIgnoreCase); + condition = o => !o.ToString().Equals(xlFilter.Value.ToString(), StringComparison.OrdinalIgnoreCase); else condition = o => (o as IComparable).CompareTo(xlFilter.Value) != 0; break; @@ -1927,7 +1921,7 @@ if (isText) { xlFilter.Value = filter.Val.Value; - condition = o => o.ToString().Equals(xlFilter.Value.ToString(), StringComparison.InvariantCultureIgnoreCase); + condition = o => o.ToString().Equals(xlFilter.Value.ToString(), StringComparison.OrdinalIgnoreCase); } else { @@ -2094,7 +2088,7 @@ foreach (DataValidation dvs in dataValidations.Elements()) { String txt = dvs.SequenceOfReferences.InnerText; - if (String.IsNullOrWhiteSpace(txt)) continue; + if (XLHelper.IsNullOrWhiteSpace(txt)) continue; foreach (var rangeAddress in txt.Split(' ')) { using (var range = ws.Range(rangeAddress)) @@ -2150,7 +2144,7 @@ if (conditionalFormat.ConditionalFormatType == XLConditionalFormatType.CellIs && fr.Operator != null) conditionalFormat.Operator = fr.Operator.Value.ToClosedXml(); - if (fr.Text != null && !String.IsNullOrWhiteSpace(fr.Text)) + if (fr.Text != null && !XLHelper.IsNullOrWhiteSpace(fr.Text)) conditionalFormat.Values.Add(GetFormula(fr.Text.Value)); if (conditionalFormat.ConditionalFormatType == XLConditionalFormatType.Top10) @@ -2182,8 +2176,8 @@ conditionalFormat.ShowBarOnly = !dataBar.ShowValue.Value; var id = fr.Descendants().FirstOrDefault(); - if (id != null && id.Text != null && !String.IsNullOrWhiteSpace(id.Text)) - conditionalFormat.Id = Guid.Parse(id.Text.Substring(1, id.Text.Length - 2)); + if (id != null && id.Text != null && !XLHelper.IsNullOrWhiteSpace(id.Text)) + conditionalFormat.Id = new Guid(id.Text.Substring(1, id.Text.Length - 2)); ExtractConditionalFormatValueObjects(conditionalFormat, dataBar); } diff --git a/ClosedXML/Excel/XLWorkbook_Save.cs b/ClosedXML/Excel/XLWorkbook_Save.cs index 9e536de..0ba0cdc 100644 --- a/ClosedXML/Excel/XLWorkbook_Save.cs +++ b/ClosedXML/Excel/XLWorkbook_Save.cs @@ -235,12 +235,12 @@ // Ensure all RelId's have been added to the context context.RelIdGenerator.AddValues(workbookPart.Parts.Select(p => p.RelationshipId), RelType.Workbook); - context.RelIdGenerator.AddValues(WorksheetsInternal.Cast().Where(ws => !String.IsNullOrWhiteSpace(ws.RelId)).Select(ws => ws.RelId), RelType.Workbook); - context.RelIdGenerator.AddValues(WorksheetsInternal.Cast().Where(ws => !String.IsNullOrWhiteSpace(ws.LegacyDrawingId)).Select(ws => ws.LegacyDrawingId), RelType.Workbook); + context.RelIdGenerator.AddValues(WorksheetsInternal.Cast().Where(ws => !XLHelper.IsNullOrWhiteSpace(ws.RelId)).Select(ws => ws.RelId), RelType.Workbook); + context.RelIdGenerator.AddValues(WorksheetsInternal.Cast().Where(ws => !XLHelper.IsNullOrWhiteSpace(ws.LegacyDrawingId)).Select(ws => ws.LegacyDrawingId), RelType.Workbook); context.RelIdGenerator.AddValues(WorksheetsInternal .Cast() .SelectMany(ws => ws.Tables.Cast()) - .Where(t => !String.IsNullOrWhiteSpace(t.RelId)) + .Where(t => !XLHelper.IsNullOrWhiteSpace(t.RelId)) .Select(t => t.RelId), RelType.Workbook); var extendedFilePropertiesPart = document.ExtendedFilePropertiesPart ?? @@ -292,7 +292,7 @@ var vmlDrawingPart = worksheetPart.VmlDrawingParts.FirstOrDefault(); if (vmlDrawingPart == null) { - if (String.IsNullOrWhiteSpace(worksheet.LegacyDrawingId)) + if (XLHelper.IsNullOrWhiteSpace(worksheet.LegacyDrawingId)) { worksheet.LegacyDrawingId = context.RelIdGenerator.GetNext(RelType.Workbook); worksheet.LegacyDrawingIsNew = true; @@ -358,7 +358,8 @@ // Only delete the VmlDrawingParts for comments. if (vmlDrawingPart != null) { - var xdoc = XDocumentExtensions.Load(vmlDrawingPart.GetStream(FileMode.Open)); + var vmlStream = vmlDrawingPart.GetStream(FileMode.Open); + var xdoc = XDocumentExtensions.Load(vmlStream); //xdoc.Root.Elements().Where(e => e.Name.LocalName == "shapelayout").Remove(); xdoc.Root.Elements().Where( e => e.Name.LocalName == "shapetype" && (string)e.Attribute("id") == @"_x0000_t202").Remove(); @@ -388,6 +389,7 @@ legacyParts.ForEach(p => vmlDrawingPartNew.AddPart(p, vmlDrawingPart.GetIdOfPart(p))); } + vmlStream.Close(); worksheetPart.DeletePart(vmlDrawingPart); if (hasNewPart && rId != worksheetPart.GetIdOfPart(vmlDrawingPartNew)) @@ -508,7 +510,7 @@ if (Properties.Manager != null) { - if (!String.IsNullOrWhiteSpace(Properties.Manager)) + if (!XLHelper.IsNullOrWhiteSpace(Properties.Manager)) { if (properties.Manager == null) properties.Manager = new Manager(); @@ -521,7 +523,7 @@ if (Properties.Company == null) return; - if (!String.IsNullOrWhiteSpace(Properties.Company)) + if (!XLHelper.IsNullOrWhiteSpace(Properties.Company)) { if (properties.Company == null) properties.Company = new Company(); @@ -651,7 +653,7 @@ foreach (var xlSheet in WorksheetsInternal.Cast().OrderBy(w => w.Position)) { string rId; - if (xlSheet.SheetId == 0 && String.IsNullOrWhiteSpace(xlSheet.RelId)) + if (xlSheet.SheetId == 0 && XLHelper.IsNullOrWhiteSpace(xlSheet.RelId)) { rId = context.RelIdGenerator.GetNext(RelType.Workbook); @@ -663,7 +665,7 @@ } else { - if (String.IsNullOrWhiteSpace(xlSheet.RelId)) + if (XLHelper.IsNullOrWhiteSpace(xlSheet.RelId)) { rId = String.Concat("rId", xlSheet.SheetId); context.RelIdGenerator.AddValues(new List { rId }, RelType.Workbook); @@ -810,7 +812,7 @@ if (!nr.Visible) definedName.Hidden = BooleanValue.FromBoolean(true); - if (!String.IsNullOrWhiteSpace(nr.Comment)) + if (!XLHelper.IsNullOrWhiteSpace(nr.Comment)) definedName.Comment = nr.Comment; definedNames.AppendChild(definedName); } @@ -864,7 +866,7 @@ if (!nr.Visible) definedName.Hidden = BooleanValue.FromBoolean(true); - if (!String.IsNullOrWhiteSpace(nr.Comment)) + if (!XLHelper.IsNullOrWhiteSpace(nr.Comment)) definedName.Comment = nr.Comment; definedNames.AppendChild(definedName); } @@ -910,7 +912,7 @@ w.Internals.CellsCollection.GetCells( c => ((c.DataType == XLDataType.Text && c.ShareString) || c.HasRichText) && (c as XLCell).InnerText.Length > 0 - && String.IsNullOrWhiteSpace(c.FormulaA1) + && XLHelper.IsNullOrWhiteSpace(c.FormulaA1) ))) { c.DataType = XLDataType.Text; @@ -1061,7 +1063,7 @@ var cellsWithoutFormulas = new HashSet(); foreach (var c in worksheet.Internals.CellsCollection.GetCells()) { - if (String.IsNullOrWhiteSpace(c.FormulaA1)) + if (XLHelper.IsNullOrWhiteSpace(c.FormulaA1)) cellsWithoutFormulas.Add(c.Address.ToStringRelative()); else { @@ -1803,6 +1805,20 @@ var modified = Properties.Modified == DateTime.MinValue ? DateTime.Now : Properties.Modified; document.PackageProperties.Created = created; document.PackageProperties.Modified = modified; + +#if true // Workaround: https://github.com/OfficeDev/Open-XML-SDK/issues/235 + + if (Properties.LastModifiedBy == null) document.PackageProperties.LastModifiedBy = ""; + if (Properties.Author == null) document.PackageProperties.Creator = ""; + if (Properties.Title == null) document.PackageProperties.Title = ""; + if (Properties.Subject == null) document.PackageProperties.Subject = ""; + if (Properties.Category == null) document.PackageProperties.Category = ""; + if (Properties.Keywords == null) document.PackageProperties.Keywords = ""; + if (Properties.Comments == null) document.PackageProperties.Description = ""; + if (Properties.Status == null) document.PackageProperties.ContentStatus = ""; + +#endif + document.PackageProperties.LastModifiedBy = Properties.LastModifiedBy; document.PackageProperties.Creator = Properties.Author; @@ -1891,7 +1907,7 @@ while (formula.StartsWith("=") && formula.Length > 1) formula = formula.Substring(1); - if (!String.IsNullOrWhiteSpace(formula)) + if (!XLHelper.IsNullOrWhiteSpace(formula)) { tableColumn.CalculatedColumnFormula = new CalculatedColumnFormula { @@ -1912,7 +1928,7 @@ tableColumn.TotalsRowFormula = new TotalsRowFormula(xlField.TotalsRowFormulaA1); } - if (!String.IsNullOrWhiteSpace(xlField.TotalsRowLabel)) + if (!XLHelper.IsNullOrWhiteSpace(xlField.TotalsRowLabel)) tableColumn.TotalsRowLabel = xlField.TotalsRowLabel; } tableColumns.AppendChild(tableColumn); @@ -1975,7 +1991,7 @@ PivotCache pivotCache; PivotTableCacheDefinitionPart pivotTableCacheDefinitionPart; - if (!String.IsNullOrWhiteSpace(pt.WorkbookCacheRelId)) + if (!XLHelper.IsNullOrWhiteSpace(pt.WorkbookCacheRelId)) { pivotCache = pivotCaches.Cast().Single(pc => pc.Id.Value == pt.WorkbookCacheRelId); pivotTableCacheDefinitionPart = workbookPart.GetPartById(pt.WorkbookCacheRelId) as PivotTableCacheDefinitionPart; @@ -1989,18 +2005,18 @@ GeneratePivotTableCacheDefinitionPartContent(pivotTableCacheDefinitionPart, pt, context); - if (String.IsNullOrWhiteSpace(pt.WorkbookCacheRelId)) + if (XLHelper.IsNullOrWhiteSpace(pt.WorkbookCacheRelId)) pivotCaches.AppendChild(pivotCache); PivotTablePart pivotTablePart; - if (String.IsNullOrWhiteSpace(pt.RelId)) + if (XLHelper.IsNullOrWhiteSpace(pt.RelId)) pivotTablePart = worksheetPart.AddNewPart(context.RelIdGenerator.GetNext(RelType.Workbook)); else pivotTablePart = worksheetPart.GetPartById(pt.RelId) as PivotTablePart; GeneratePivotTablePartContent(pivotTablePart, pt, pivotCache.CacheId, context); - if (String.IsNullOrWhiteSpace(pt.RelId)) + if (XLHelper.IsNullOrWhiteSpace(pt.RelId)) pivotTablePart.AddPart(pivotTableCacheDefinitionPart, context.RelIdGenerator.GetNext(RelType.Workbook)); } } @@ -2124,8 +2140,8 @@ ptfi.DataType = XLDataType.DateTime; ptfi.MixedDataType = false; ptfi.DistinctValues = fieldValueCells - .Select(cell => cell.GetDateTime()) - .Distinct() + .Select(cell => cell.GetDateTime()) + .Distinct() .Cast() .ToArray(); @@ -2193,7 +2209,7 @@ var pivotCacheRecords = new PivotCacheRecords(); pivotCacheRecords.AddNamespaceDeclaration("r", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships"); + "http://schemas.openxmlformats.org/officeDocument/2006/relationships"); pivotTableCacheRecordsPart.PivotCacheRecords = pivotCacheRecords; context.PivotTables.Add(pti.Guid, pti); @@ -2775,9 +2791,10 @@ SaveContext context) { var ms = new MemoryStream(); - CopyStream(vmlDrawingPart.GetStream(FileMode.OpenOrCreate), ms); + var stream = vmlDrawingPart.GetStream(FileMode.OpenOrCreate); + CopyStream(stream, ms); ms.Position = 0; - var writer = new XmlTextWriter(vmlDrawingPart.GetStream(FileMode.Create), Encoding.UTF8); + var writer = new XmlTextWriter(stream, Encoding.UTF8); writer.WriteStartElement("xml"); @@ -2864,7 +2881,7 @@ StrokeWeight = String.Concat(c.Comment.Style.ColorsAndLines.LineWeight.ToInvariantString(), "pt"), InsetMode = c.Comment.Style.Margins.Automatic ? InsetMarginValues.Auto : InsetMarginValues.Custom }; - if (!String.IsNullOrWhiteSpace(c.Comment.Style.Web.AlternateText)) + if (!XLHelper.IsNullOrWhiteSpace(c.Comment.Style.Web.AlternateText)) shape.Alternate = c.Comment.Style.Web.AlternateText; return shape; @@ -2955,41 +2972,42 @@ { case Drawings.XLPicturePlacement.FreeFloating: var absoluteAnchor = new Xdr.AbsoluteAnchor( - new Xdr.Position - { - X = ConvertToEnglishMetricUnits(pic.Left, GraphicsUtils.Graphics.DpiX), - Y = ConvertToEnglishMetricUnits(pic.Top, GraphicsUtils.Graphics.DpiY) - }, - new Xdr.Extent - { - Cx = extentsCx, - Cy = extentsCy - }, - new Xdr.Picture( - new Xdr.NonVisualPictureProperties( + new Xdr.Position + { + X = ConvertToEnglishMetricUnits(pic.Left, GraphicsUtils.Graphics.DpiX), + Y = ConvertToEnglishMetricUnits(pic.Top, GraphicsUtils.Graphics.DpiY) + }, + new Xdr.Extent + { + Cx = extentsCx, + Cy = extentsCy + }, + new Xdr.Picture( + new Xdr.NonVisualPictureProperties( new Xdr.NonVisualDrawingProperties { Id = nvpId, Name = pic.Name }, new Xdr.NonVisualPictureDrawingProperties(new PictureLocks { NoChangeAspect = true }) - ), - new Xdr.BlipFill( - new Blip { Embed = drawingsPart.GetIdOfPart(imagePart), CompressionState = BlipCompressionValues.Print }, - new Stretch(new FillRectangle()) - ), - new Xdr.ShapeProperties( - new Transform2D( - new Offset { X = 0, Y = 0 }, - new Extents { Cx = extentsCx, Cy = extentsCy } - ), - new PresetGeometry { Preset = ShapeTypeValues.Rectangle } - ) ), - new Xdr.ClientData() - ); + new Xdr.BlipFill( + new Blip { Embed = drawingsPart.GetIdOfPart(imagePart), CompressionState = BlipCompressionValues.Print }, + new Stretch(new FillRectangle()) + ), + new Xdr.ShapeProperties( + new Transform2D( + new Offset { X = 0, Y = 0 }, + new Extents { Cx = extentsCx, Cy = extentsCy } + ), + new PresetGeometry { Preset = ShapeTypeValues.Rectangle } + ) + ), + new Xdr.ClientData() + ); worksheetDrawing.Append(absoluteAnchor); break; case Drawings.XLPicturePlacement.MoveAndSize: var moveAndSizeFromMarker = pic.Markers[Drawings.XLMarkerPosition.TopLeft]; + if (moveAndSizeFromMarker == null) moveAndSizeFromMarker = new Drawings.XLMarker(picture.Worksheet.Cell("A1").Address); fMark = new Xdr.FromMarker { ColumnId = new Xdr.ColumnId((moveAndSizeFromMarker.Address.ColumnNumber - 1).ToString()), @@ -2999,6 +3017,7 @@ }; var moveAndSizeToMarker = pic.Markers[Drawings.XLMarkerPosition.BottomRight]; + if (moveAndSizeToMarker == null) moveAndSizeToMarker = new Drawings.XLMarker(picture.Worksheet.Cell("A1").Address, new System.Drawing.Point(picture.Width, picture.Height)); tMark = new Xdr.ToMarker { ColumnId = new Xdr.ColumnId((moveAndSizeToMarker.Address.ColumnNumber - 1).ToString()), @@ -3035,6 +3054,7 @@ case Drawings.XLPicturePlacement.Move: var moveFromMarker = pic.Markers[Drawings.XLMarkerPosition.TopLeft]; + if (moveFromMarker == null) moveFromMarker = new Drawings.XLMarker(picture.Worksheet.Cell("A1").Address); fMark = new Xdr.FromMarker { ColumnId = new Xdr.ColumnId((moveFromMarker.Address.ColumnNumber - 1).ToString()), @@ -3461,7 +3481,7 @@ if (diffFont?.HasChildren ?? false) differentialFormat.Append(diffFont); - if (!String.IsNullOrWhiteSpace(cf.Style.NumberFormat.Format)) + if (!XLHelper.IsNullOrWhiteSpace(cf.Style.NumberFormat.Format)) { var numberFormat = new NumberingFormat { @@ -3493,7 +3513,7 @@ if (diffFont?.HasChildren ?? false) differentialFormat.Append(diffFont); - if (!String.IsNullOrWhiteSpace(style.NumberFormat.Format) || style.NumberFormat.NumberFormatId != 0) + if (!XLHelper.IsNullOrWhiteSpace(style.NumberFormat.Format) || style.NumberFormat.NumberFormatId != 0) { var numberFormat = new NumberingFormat(); @@ -4242,7 +4262,7 @@ { var newXLNumberFormat = new XLNumberFormat(); - if (nf.FormatCode != null && !String.IsNullOrWhiteSpace(nf.FormatCode.Value)) + if (nf.FormatCode != null && !XLHelper.IsNullOrWhiteSpace(nf.FormatCode.Value)) newXLNumberFormat.Format = nf.FormatCode.Value; else if (nf.NumberFormatId != null) newXLNumberFormat.NumberFormatId = (Int32)nf.NumberFormatId.Value; @@ -4438,13 +4458,13 @@ var seqRef = new List { selection.ActiveCell.Value }; seqRef.AddRange(xlWorksheet.SelectedRanges - .Select(range => - { - if (range.RangeAddress.FirstAddress.Equals(range.RangeAddress.LastAddress)) - return range.RangeAddress.FirstAddress.ToStringRelative(false); - else - return range.RangeAddress.ToStringRelative(false); - })); + .Select(range => + { + if (range.RangeAddress.FirstAddress.Equals(range.RangeAddress.LastAddress)) + return range.RangeAddress.FirstAddress.ToStringRelative(false); + else + return range.RangeAddress.ToStringRelative(false); + })); selection.SequenceOfReferences = new ListValue { InnerText = String.Join(" ", seqRef.Distinct().ToArray()) }; @@ -4838,7 +4858,7 @@ var table = xlWorksheet.Tables.First(t => t.AsRange().Contains(xlCell)); field = table.Fields.First(f => f.Column.ColumnNumber() == xlCell.Address.ColumnNumber) as XLTableField; - if (!String.IsNullOrWhiteSpace(field.TotalsRowLabel)) + if (!XLHelper.IsNullOrWhiteSpace(field.TotalsRowLabel)) { cell.DataType = XLWorkbook.CvSharedString; } @@ -4921,7 +4941,7 @@ var protection = xlWorksheet.Protection; sheetProtection.Sheet = protection.Protected; - if (!String.IsNullOrWhiteSpace(protection.PasswordHash)) + if (!XLHelper.IsNullOrWhiteSpace(protection.PasswordHash)) sheetProtection.Password = protection.PasswordHash; sheetProtection.FormatCells = OpenXmlHelper.GetBooleanValue(!protection.FormatCells, true); sheetProtection.FormatColumns = OpenXmlHelper.GetBooleanValue(!protection.FormatColumns, true); @@ -5176,7 +5196,7 @@ Display = hl.Cell.GetFormattedString() }; } - if (!String.IsNullOrWhiteSpace(hl.Tooltip)) + if (!XLHelper.IsNullOrWhiteSpace(hl.Tooltip)) hyperlink.Tooltip = hl.Tooltip; hyperlinks.AppendChild(hyperlink); } @@ -5503,7 +5523,7 @@ { if (field != null) { - if (!String.IsNullOrWhiteSpace(field.TotalsRowLabel)) + if (!XLHelper.IsNullOrWhiteSpace(field.TotalsRowLabel)) { var cellValue = new CellValue(); cellValue.Text = xlCell.SharedStringId.ToString(); @@ -5569,7 +5589,7 @@ } else if (dataType == XLDataType.DateTime || dataType == XLDataType.Number) { - if (!String.IsNullOrWhiteSpace(xlCell.InnerText)) + if (!XLHelper.IsNullOrWhiteSpace(xlCell.InnerText)) { var cellValue = new CellValue(); var d = Double.Parse(xlCell.InnerText, XLHelper.NumberStyle, XLHelper.ParseCulture); diff --git a/ClosedXML/Excel/XLWorksheet.cs b/ClosedXML/Excel/XLWorksheet.cs index 1868c12..9d2ba32 100644 --- a/ClosedXML/Excel/XLWorksheet.cs +++ b/ClosedXML/Excel/XLWorksheet.cs @@ -174,7 +174,7 @@ throw new ArgumentException("Worksheet names cannot contain any of the following characters: " + InvalidNameChars); - if (String.IsNullOrWhiteSpace(value)) + if (XLHelper.IsNullOrWhiteSpace(value)) throw new ArgumentException("Worksheet names cannot be empty"); if (value.Length > 31) diff --git a/ClosedXML/Excel/XLWorksheets.cs b/ClosedXML/Excel/XLWorksheets.cs index 94cace4..01aa54b 100644 --- a/ClosedXML/Excel/XLWorksheets.cs +++ b/ClosedXML/Excel/XLWorksheets.cs @@ -130,7 +130,7 @@ "Can't delete the worksheet because there are multiple worksheets associated with that index."); var ws = _worksheets.Values.Single(w => w.Position == position); - if (!String.IsNullOrWhiteSpace(ws.RelId) && !Deleted.Contains(ws.RelId)) + if (!XLHelper.IsNullOrWhiteSpace(ws.RelId) && !Deleted.Contains(ws.RelId)) Deleted.Add(ws.RelId); _worksheets.RemoveAll(w => w.Position == position); @@ -171,7 +171,7 @@ public void Rename(String oldSheetName, String newSheetName) { - if (String.IsNullOrWhiteSpace(oldSheetName) || !_worksheets.ContainsKey(oldSheetName.ToLowerInvariant())) return; + if (XLHelper.IsNullOrWhiteSpace(oldSheetName) || !_worksheets.ContainsKey(oldSheetName.ToLowerInvariant())) return; if (!oldSheetName.Equals(newSheetName, StringComparison.OrdinalIgnoreCase) && _worksheets.Any(ws1 => ws1.Key.Equals(newSheetName, StringComparison.OrdinalIgnoreCase))) diff --git a/ClosedXML/Extensions.cs b/ClosedXML/Extensions.cs index 8836f26..88c1f8d 100644 --- a/ClosedXML/Extensions.cs +++ b/ClosedXML/Extensions.cs @@ -213,47 +213,25 @@ public static class FontBaseExtensions { - private static Font GetCachedFont(IXLFontBase fontBase, Dictionary fontCache) - { - Font font; - if (!fontCache.TryGetValue(fontBase, out font)) - { - font = new Font(fontBase.FontName, (float)fontBase.FontSize, GetFontStyle(fontBase)); - fontCache.Add(fontBase, font); - } - return font; - } - public static Double GetWidth(this IXLFontBase fontBase, String text, Dictionary fontCache) { - if (String.IsNullOrWhiteSpace(text)) + if (XLHelper.IsNullOrWhiteSpace(text)) return 0; var font = GetCachedFont(fontBase, fontCache); + var textWidth = GraphicsUtils.MeasureString(text, font).Width; - var textSize = GraphicsUtils.MeasureString(text, font); - - double width = (((textSize.Width / (double)7) * 256) - (128 / 7)) / 256; + double width = (textWidth / 7d * 256 - 128 / 7) / 256; width = Math.Round(width + 0.2, 2); return width; } - private static FontStyle GetFontStyle(IXLFontBase font) - { - FontStyle fontStyle = FontStyle.Regular; - if (font.Bold) fontStyle |= FontStyle.Bold; - if (font.Italic) fontStyle |= FontStyle.Italic; - if (font.Strikethrough) fontStyle |= FontStyle.Strikeout; - if (font.Underline != XLFontUnderlineValues.None) fontStyle |= FontStyle.Underline; - return fontStyle; - } - public static Double GetHeight(this IXLFontBase fontBase, Dictionary fontCache) { var font = GetCachedFont(fontBase, fontCache); - var textSize = GraphicsUtils.MeasureString("X", font); - return (double)textSize.Height * 0.85; + var textHeight = GraphicsUtils.MeasureString("X", font).Height; + return (double)textHeight * 0.85; } public static void CopyFont(this IXLFontBase font, IXLFontBase sourceFont) @@ -270,6 +248,27 @@ font.FontFamilyNumbering = sourceFont.FontFamilyNumbering; font.FontCharSet = sourceFont.FontCharSet; } + + private static Font GetCachedFont(IXLFontBase fontBase, Dictionary fontCache) + { + Font font; + if (!fontCache.TryGetValue(fontBase, out font)) + { + font = new Font(fontBase.FontName, (float)fontBase.FontSize, GetFontStyle(fontBase)); + fontCache.Add(fontBase, font); + } + return font; + } + + private static FontStyle GetFontStyle(IXLFontBase font) + { + FontStyle fontStyle = FontStyle.Regular; + if (font.Bold) fontStyle |= FontStyle.Bold; + if (font.Italic) fontStyle |= FontStyle.Italic; + if (font.Strikethrough) fontStyle |= FontStyle.Strikeout; + if (font.Underline != XLFontUnderlineValues.None) fontStyle |= FontStyle.Underline; + return fontStyle; + } } public static class XDocumentExtensions diff --git a/ClosedXML/Properties/AssemblyInfo.cs b/ClosedXML/Properties/AssemblyInfo.cs index 92b76d7..ddf1df5 100644 --- a/ClosedXML/Properties/AssemblyInfo.cs +++ b/ClosedXML/Properties/AssemblyInfo.cs @@ -1,24 +1 @@ -using System.Reflection; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ClosedXML")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ClosedXML")] -[assembly: AssemblyCopyright("Copyright © Manuel De Leon 2014")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("8747331d-de58-4621-8c7f-a7d57ca3467a")] - -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ClosedXML_Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a1fb8ba59167fe734d64128ca73d32c45cb8a117246d09c95c8769db88fe332b0a3396bedd0ea48ee42b0e5796fec0798ca5cb628a9a6de80d35d6c67b936ca1670347b3d4f2b769c8ce2ddcf959dbac6bcd88e6c08751ea1fffa0522de3507193e7035305a8aa008d6c88cca1341b3120fa9c347ab3f97e2d772e2709277da5")] +[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ClosedXML_Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a1fb8ba59167fe734d64128ca73d32c45cb8a117246d09c95c8769db88fe332b0a3396bedd0ea48ee42b0e5796fec0798ca5cb628a9a6de80d35d6c67b936ca1670347b3d4f2b769c8ce2ddcf959dbac6bcd88e6c08751ea1fffa0522de3507193e7035305a8aa008d6c88cca1341b3120fa9c347ab3f97e2d772e2709277da5")] diff --git a/ClosedXML/Properties/AssemblyVersionInfo.cs b/ClosedXML/Properties/AssemblyVersionInfo.cs deleted file mode 100644 index da0403f..0000000 --- a/ClosedXML/Properties/AssemblyVersionInfo.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Reflection; - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("0.92.0.0")] -[assembly: AssemblyFileVersion("0.92.0.0")] -[assembly: AssemblyInformationalVersion("0.92.0")] diff --git a/ClosedXML/Utils/GraphicsUtils.cs b/ClosedXML/Utils/GraphicsUtils.cs index 3af3d33..f0f7644 100644 --- a/ClosedXML/Utils/GraphicsUtils.cs +++ b/ClosedXML/Utils/GraphicsUtils.cs @@ -7,6 +7,7 @@ { [ThreadStatic] private static Graphics threadLocalGraphics; + internal static Graphics Graphics { get diff --git a/ClosedXML/XLHelper.cs b/ClosedXML/XLHelper.cs index 1c1081d..6f25f72 100644 --- a/ClosedXML/XLHelper.cs +++ b/ClosedXML/XLHelper.cs @@ -1,12 +1,11 @@ using System; +using System.Drawing; using System.Globalization; +using System.Linq; +using System.Text.RegularExpressions; namespace ClosedXML.Excel { - using System.Drawing; - using System.Linq; - using System.Text.RegularExpressions; - /// /// Common methods /// @@ -19,7 +18,8 @@ public const String MaxColumnLetter = "XFD"; public const Double Epsilon = 1e-10; - private const Int32 TwoT26 = 26 * 26; + private const Int32 TwoT26 = 26*26; + internal static readonly Graphics Graphic = Graphics.FromImage(new Bitmap(200, 200)); internal static readonly Double DpiX = Graphic.DpiX; internal static readonly NumberStyles NumberStyle = NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowExponent; @@ -85,9 +85,9 @@ private static readonly string[] letters = new[] { "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" }; /// - /// Gets the column letter of a given column number. + /// Gets the column letter of a given column number. /// - /// The column number to translate into a column letter. + /// The column number to translate into a column letter. /// if set to true the column letter will be restricted to the allowed range. /// public static string GetColumnLetterFromNumber(int columnNumber, bool trimToAllowed = false) @@ -117,7 +117,7 @@ public static bool IsValidColumn(string column) { var length = column.Length; - if (String.IsNullOrWhiteSpace(column) || length > 3) + if (XLHelper.IsNullOrWhiteSpace(column) || length > 3) return false; var theColumn = column.ToUpper(); @@ -153,7 +153,7 @@ public static bool IsValidA1Address(string address) { - if (String.IsNullOrWhiteSpace(address)) + if (XLHelper.IsNullOrWhiteSpace(address)) return false; address = address.Replace("$", ""); @@ -226,6 +226,16 @@ return rows; } + + public static bool IsNullOrWhiteSpace(string value) + { +#if _NET35_ + if (value == null) return true; + return value.All(c => char.IsWhiteSpace(c)); +#else + return String.IsNullOrWhiteSpace(value); +#endif + } private static readonly Regex A1RegexRelative = new Regex( @"(?<=\W)(?\$?[a-zA-Z]{1,3}\$?\d{1,7})(?=\W)" // A1 + @"|(?<=\W)(?\$?\d{1,7}:\$?\d{1,7})(?=\W)" // 1:1 diff --git a/ClosedXML/packages.config b/ClosedXML/packages.config deleted file mode 100644 index ae92076..0000000 --- a/ClosedXML/packages.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/ClosedXML_Examples/ClosedXML_Examples.csproj b/ClosedXML_Examples/ClosedXML_Examples.csproj index dca9ada..5eb03a1 100644 --- a/ClosedXML_Examples/ClosedXML_Examples.csproj +++ b/ClosedXML_Examples/ClosedXML_Examples.csproj @@ -1,208 +1,37 @@ - - + + - Debug - x86 - 8.0.30703 - 2.0 - {03A518D0-1CB7-488E-861C-C4E782B27A46} + netcoreapp2.0;net40;net46 Exe - Properties - ClosedXML_Examples - ClosedXML_Examples - v4.0 - - - 512 - ..\ - true - - - true - bin\Debug\ - DEBUG;TRACE - full - AnyCPU - prompt - false - 6 - - - bin\Release\ - TRACE - true - pdbonly - AnyCPU - prompt - false - 6 - - - ClosedXML_Examples.Program - - true - - ClosedXML.snk + $(NoWarn);NU1605 - - true + + + $(DefineConstants);_NETSTANDARD_;_NETSTANDARD2_0_ + + + $(DefineConstants);_NETFRAMEWORK_;_NET40_ + + + + $(DefineConstants);_NETFRAMEWORK_;_NET46_ + + - - ..\packages\DocumentFormat.OpenXml.2.7.2\lib\net40\DocumentFormat.OpenXml.dll - True - - - - - - - - - - - + + + - - Properties\AssemblyVersionInfo.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - .editorconfig - - - - + + - - - {BD5E6BFE-E837-4A35-BCA9-39667D873A20} - ClosedXML - - - - - - - - - - - - - - \ No newline at end of file + + diff --git a/ClosedXML_Examples/Creating/CreateFiles.cs b/ClosedXML_Examples/Creating/CreateFiles.cs index 8f1978f..c61315c 100644 --- a/ClosedXML_Examples/Creating/CreateFiles.cs +++ b/ClosedXML_Examples/Creating/CreateFiles.cs @@ -88,7 +88,7 @@ new ShiftingFormulas().Create(Path.Combine(path, "ShiftingFormulas.xlsx")); new CopyingRowsAndColumns().Create(Path.Combine(path, "CopyingRowsAndColumns.xlsx")); new UsingRichText().Create(Path.Combine(path, "UsingRichText.xlsx")); - new UsingPhonetics().Create(Path.Combine(path, "UsingPhonetics.xlsx")); + //new UsingPhonetics().Create(Path.Combine(path, "UsingPhonetics.xlsx")); new WalkingRanges().Create(Path.Combine(path, "CellMoves.xlsx")); new AddingComments().Create(Path.Combine(path, "AddingComments.xlsx")); new PivotTables().Create(Path.Combine(path, "PivotTables.xlsx")); diff --git a/ClosedXML_Examples/Properties/AssemblyInfo.cs b/ClosedXML_Examples/Properties/AssemblyInfo.cs deleted file mode 100644 index c7e7b8b..0000000 --- a/ClosedXML_Examples/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Reflection; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ClosedXML_Examples")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("ClosedXML_Examples")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("603cd89c-23f2-415e-8afc-2e9ab7a4c372")] diff --git a/ClosedXML_Examples/Styles/UsingColors.cs b/ClosedXML_Examples/Styles/UsingColors.cs index 9364c15..54fea8f 100644 --- a/ClosedXML_Examples/Styles/UsingColors.cs +++ b/ClosedXML_Examples/Styles/UsingColors.cs @@ -61,12 +61,6 @@ ro++; - // FromKnownColor(KnownColor knownColor) - ws.Cell(++ro, 1).Style.Fill.BackgroundColor = XLColor.FromKnownColor(KnownColor.Plum); - ws.Cell(ro, 2).Value = "XLColor.FromKnownColor(KnownColor.Plum)"; - - ro++; - // FromName(String colorName) ws.Cell(++ro, 1).Style.Fill.BackgroundColor = XLColor.FromName("PowderBlue"); ws.Cell(ro, 2).Value = "XLColor.FromName(\"PowderBlue\")"; @@ -87,4 +81,4 @@ wb.SaveAs(filePath); } } -} \ No newline at end of file +} diff --git a/ClosedXML_Examples/app.config b/ClosedXML_Examples/app.config index 86fcc8b..21ac8f3 100644 --- a/ClosedXML_Examples/app.config +++ b/ClosedXML_Examples/app.config @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/ClosedXML_Examples/packages.config b/ClosedXML_Examples/packages.config deleted file mode 100644 index becf24f..0000000 --- a/ClosedXML_Examples/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/ClosedXML_Sandbox/ClosedXML_Sandbox.csproj b/ClosedXML_Sandbox/ClosedXML_Sandbox.csproj index 7931620..ae32cec 100644 --- a/ClosedXML_Sandbox/ClosedXML_Sandbox.csproj +++ b/ClosedXML_Sandbox/ClosedXML_Sandbox.csproj @@ -1,92 +1,43 @@ - - + + - Debug - x86 - 8.0.30703 - 2.0 - {38B882F0-E6F2-45C5-9BE9-CDC27FBEB4AB} Exe - Properties - ClosedXML_Sandbox - ClosedXML_Sandbox - v4.0 - 512 - ..\ - true - + netcoreapp2.0;net40;net46 + $(NoWarn);NU1605 - - true - bin\Debug\ - DEBUG;TRACE - full - AnyCPU - prompt - false - 6 + + + $(DefineConstants);_NETSTANDARD_;_NETSTANDARD2_0_ - - bin\Release\ - TRACE - true - pdbonly - AnyCPU - prompt - false - 6 + + + $(DefineConstants);_NETFRAMEWORK_;_NET40_ - - - ..\packages\DocumentFormat.OpenXml.2.7.2\lib\net40\DocumentFormat.OpenXml.dll - True - - + + + $(DefineConstants);_NETFRAMEWORK_;_NET46_ + + + + + + - - - - - - - - - - - Properties\AssemblyVersionInfo.cs - - - - - + + + + - - .editorconfig - - - - + + PreserveNewest + - - {bd5e6bfe-e837-4a35-bca9-39667d873a20} - ClosedXML - - - {03A518D0-1CB7-488E-861C-C4E782B27A46} - ClosedXML_Examples - + - - - \ No newline at end of file + + diff --git a/ClosedXML_Sandbox/Properties/AssemblyInfo.cs b/ClosedXML_Sandbox/Properties/AssemblyInfo.cs deleted file mode 100644 index a2c5998..0000000 --- a/ClosedXML_Sandbox/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ClosedXML_Sandbox")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("ClosedXML_Sandbox")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("7a3783fd-4e1b-4c17-a745-e6bbb593bd45")] diff --git a/ClosedXML_Sandbox/ReflectionExtensions.cs b/ClosedXML_Sandbox/ReflectionExtensions.cs new file mode 100644 index 0000000..7229a8c --- /dev/null +++ b/ClosedXML_Sandbox/ReflectionExtensions.cs @@ -0,0 +1,17 @@ +#if _NET40_ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Text; + +namespace ClosedXML_Sandbox +{ + internal static class ReflectionExtensions + { + public static void SetValue(this PropertyInfo info, object obj, object value) + { + info.SetValue(obj, value, null); + } + } +} +#endif diff --git a/ClosedXML_Sandbox/app.config b/ClosedXML_Sandbox/app.config index 86fcc8b..21ac8f3 100644 --- a/ClosedXML_Sandbox/app.config +++ b/ClosedXML_Sandbox/app.config @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/ClosedXML_Sandbox/packages.config b/ClosedXML_Sandbox/packages.config deleted file mode 100644 index becf24f..0000000 --- a/ClosedXML_Sandbox/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/ClosedXML_Tests/ClosedXML_Tests.csproj b/ClosedXML_Tests/ClosedXML_Tests.csproj index a49a9c8..259b639 100644 --- a/ClosedXML_Tests/ClosedXML_Tests.csproj +++ b/ClosedXML_Tests/ClosedXML_Tests.csproj @@ -1,330 +1,66 @@ - - + + - Debug - AnyCPU - - - 2.0 - {09B066ED-E4A7-4545-A1A4-FF03DD524BDF} - Library - Properties - ClosedXML_Tests - ClosedXML_Tests - v4.5.2 - 512 - {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - ..\ - true + netcoreapp2.0;net40;net46 + false + $(NoWarn);NU1605 - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(AppVeyor) - prompt - 4 - false - 6 - - - pdbonly - true - bin\Release\ - TRACE;$(AppVeyor) - prompt - 4 - false - 6 - + + $(AppVeyor) true - - ClosedXML.snk + + + $(DefineConstants);_NETSTANDARD_;_NETSTANDARD2_0_ + + + + $(DefineConstants);_NETFRAMEWORK_;_NET40_ + + + + $(DefineConstants);_NETFRAMEWORK_;_NET46_ + + - - ..\packages\DocumentFormat.OpenXml.2.7.2\lib\net40\DocumentFormat.OpenXml.dll - True - + + + + + + + + + + + + + + + + + + + + + - - ..\packages\NUnit.3.7.1\lib\net45\nunit.framework.dll - True - - - - - 3.5 - - - - - - - - - Properties\AssemblyVersionInfo.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + - - {BD5E6BFE-E837-4A35-BCA9-39667D873A20} - ClosedXML - - - {03A518D0-1CB7-488E-861C-C4E782B27A46} - ClosedXML_Examples - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - - - - - - - - - - - - - - - - - - - - .editorconfig - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + diff --git a/ClosedXML_Tests/Excel/CalcEngine/DateAndTimeTests.cs b/ClosedXML_Tests/Excel/CalcEngine/DateAndTimeTests.cs index 1d4c5d4..32e6af1 100644 --- a/ClosedXML_Tests/Excel/CalcEngine/DateAndTimeTests.cs +++ b/ClosedXML_Tests/Excel/CalcEngine/DateAndTimeTests.cs @@ -12,7 +12,7 @@ [TestFixture] public class DateAndTimeTests { - [OneTimeSetUp] + [SetUp] public void SetCultureInfo() { Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); diff --git a/ClosedXML_Tests/Excel/CalcEngine/FunctionsTests.cs b/ClosedXML_Tests/Excel/CalcEngine/FunctionsTests.cs index a4435ef..781a945 100644 --- a/ClosedXML_Tests/Excel/CalcEngine/FunctionsTests.cs +++ b/ClosedXML_Tests/Excel/CalcEngine/FunctionsTests.cs @@ -8,7 +8,7 @@ [TestFixture] public class FunctionsTests { - [OneTimeSetUp] + [SetUp] public void Init() { // Make sure tests run on a deterministic culture diff --git a/ClosedXML_Tests/Excel/CalcEngine/InformationTests.cs b/ClosedXML_Tests/Excel/CalcEngine/InformationTests.cs index 19de6ca..07b0027 100644 --- a/ClosedXML_Tests/Excel/CalcEngine/InformationTests.cs +++ b/ClosedXML_Tests/Excel/CalcEngine/InformationTests.cs @@ -9,7 +9,7 @@ [TestFixture] public class InformationTests { - [OneTimeSetUp] + [SetUp] public void SetCultureInfo() { Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); diff --git a/ClosedXML_Tests/Excel/CalcEngine/LookupTests.cs b/ClosedXML_Tests/Excel/CalcEngine/LookupTests.cs index b7b7151..ce521c9 100644 --- a/ClosedXML_Tests/Excel/CalcEngine/LookupTests.cs +++ b/ClosedXML_Tests/Excel/CalcEngine/LookupTests.cs @@ -10,7 +10,7 @@ { private XLWorkbook workbook; - [OneTimeSetUp] + [SetUp] public void Init() { // Make sure tests run on a deterministic culture diff --git a/ClosedXML_Tests/Excel/CalcEngine/StatisticalTests.cs b/ClosedXML_Tests/Excel/CalcEngine/StatisticalTests.cs index 3f451f1..34516fe 100644 --- a/ClosedXML_Tests/Excel/CalcEngine/StatisticalTests.cs +++ b/ClosedXML_Tests/Excel/CalcEngine/StatisticalTests.cs @@ -217,7 +217,7 @@ workbook.Dispose(); } - [OneTimeSetUp] + [SetUp] public void Init() { // Make sure tests run on a deterministic culture diff --git a/ClosedXML_Tests/Excel/CalcEngine/TextTests.cs b/ClosedXML_Tests/Excel/CalcEngine/TextTests.cs index b4cf9b6..3644161 100644 --- a/ClosedXML_Tests/Excel/CalcEngine/TextTests.cs +++ b/ClosedXML_Tests/Excel/CalcEngine/TextTests.cs @@ -11,7 +11,7 @@ [TestFixture] public class TextTests { - [OneTimeSetUp] + [SetUp] public void Init() { // Make sure tests run on a deterministic culture diff --git a/ClosedXML_Tests/Excel/Columns/ColumnTests.cs b/ClosedXML_Tests/Excel/Columns/ColumnTests.cs index 0d13b93..1a34b9e 100644 --- a/ClosedXML_Tests/Excel/Columns/ColumnTests.cs +++ b/ClosedXML_Tests/Excel/Columns/ColumnTests.cs @@ -3,6 +3,7 @@ using System.Linq; using ClosedXML.Excel; using NUnit.Framework; +using ClosedXML_Tests.Utils; namespace ClosedXML_Tests.Excel { @@ -107,8 +108,6 @@ IXLColumn column3 = ws.Column(3); IXLColumn columnIns = ws.Column(2).InsertColumnsBefore(1).First(); - string outputPath = Path.Combine(TestHelper.TestsOutputDirectory, "ForTesting", "Sandbox.xlsx"); - wb.SaveAs(outputPath, true); Assert.AreEqual(XLColor.Red, ws.Column(1).Cell(1).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.Red, ws.Column(1).Cell(2).Style.Fill.BackgroundColor); diff --git a/ClosedXML_Tests/Excel/Comments/CommentsTests.cs b/ClosedXML_Tests/Excel/Comments/CommentsTests.cs index 1ba4e76..34b8382 100644 --- a/ClosedXML_Tests/Excel/Comments/CommentsTests.cs +++ b/ClosedXML_Tests/Excel/Comments/CommentsTests.cs @@ -1,10 +1,6 @@ using ClosedXML.Excel; using NUnit.Framework; -using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace ClosedXML_Tests.Excel.Comments { @@ -23,11 +19,9 @@ Assert.AreEqual(XLColorType.Indexed, xlColor.ColorType); Assert.AreEqual(81, xlColor.Indexed); - var color = xlColor.Color.ToHex(); Assert.AreEqual("FF000000", color); } - } } } diff --git a/ClosedXML_Tests/Excel/ImageHandling/PictureTests.cs b/ClosedXML_Tests/Excel/ImageHandling/PictureTests.cs index 1da6ecb..a52cef1 100644 --- a/ClosedXML_Tests/Excel/ImageHandling/PictureTests.cs +++ b/ClosedXML_Tests/Excel/ImageHandling/PictureTests.cs @@ -35,6 +35,27 @@ } [Test] + public void CanAddPictureFromStream() + { + using (var wb = new XLWorkbook()) + { + var ws = wb.AddWorksheet("Sheet1"); + + using (var resourceStream = Assembly.GetAssembly(typeof(ClosedXML_Examples.BasicTable)).GetManifestResourceStream("ClosedXML_Examples.Resources.SampleImage.jpg")) + { + var picture = ws.AddPicture(resourceStream, "MyPicture") + .WithPlacement(XLPicturePlacement.FreeFloating) + .MoveTo(50, 50) + .WithSize(200, 200); + + Assert.AreEqual(XLPictureFormat.Jpeg, picture.Format); + Assert.AreEqual(200, picture.Width); + Assert.AreEqual(200, picture.Height); + } + } + } + + [Test] public void CanAddPictureFromFile() { using (var wb = new XLWorkbook()) @@ -77,9 +98,8 @@ var ws = wb.AddWorksheet("Sheet1"); using (var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ClosedXML_Tests.Resource.Images.ImageHandling.png")) - using (var bitmap = Bitmap.FromStream(resourceStream) as Bitmap) { - var pic = ws.AddPicture(bitmap, "MyPicture") + var pic = ws.AddPicture(resourceStream, "MyPicture") .WithPlacement(XLPicturePlacement.FreeFloating) .MoveTo(50, 50); @@ -251,7 +271,6 @@ Assert.AreEqual(originalCount - 2, ws.Pictures.Count); } } - } [Test] diff --git a/ClosedXML_Tests/Excel/Ranges/CopyingRangesTests.cs b/ClosedXML_Tests/Excel/Ranges/CopyingRangesTests.cs index f2b8058..45eb96c 100644 --- a/ClosedXML_Tests/Excel/Ranges/CopyingRangesTests.cs +++ b/ClosedXML_Tests/Excel/Ranges/CopyingRangesTests.cs @@ -19,7 +19,7 @@ column1.Cell(2).Style.Fill.SetBackgroundColor(XLColor.FromArgb(1, 1, 1)); column1.Cell(3).Style.Fill.SetBackgroundColor(XLColor.FromHtml("#CCCCCC")); column1.Cell(4).Style.Fill.SetBackgroundColor(XLColor.FromIndex(26)); - column1.Cell(5).Style.Fill.SetBackgroundColor(XLColor.FromKnownColor(KnownColor.MediumSeaGreen)); + column1.Cell(5).Style.Fill.SetBackgroundColor(XLColor.FromColor(Color.MediumSeaGreen)); column1.Cell(6).Style.Fill.SetBackgroundColor(XLColor.FromName("Blue")); column1.Cell(7).Style.Fill.SetBackgroundColor(XLColor.FromTheme(XLThemeColor.Accent3)); @@ -31,7 +31,7 @@ Assert.AreEqual(XLColor.FromArgb(1, 1, 1), column2.Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.FromHtml("#CCCCCC"), column2.Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.FromIndex(26), column2.Cell(4).Style.Fill.BackgroundColor); - Assert.AreEqual(XLColor.FromKnownColor(KnownColor.MediumSeaGreen), + Assert.AreEqual(XLColor.FromColor(Color.MediumSeaGreen), column2.Cell(5).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.FromName("Blue"), column2.Cell(6).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.FromTheme(XLThemeColor.Accent3), column2.Cell(7).Style.Fill.BackgroundColor); @@ -41,7 +41,7 @@ Assert.AreEqual(XLColor.FromArgb(1, 1, 1), column3.Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.FromHtml("#CCCCCC"), column3.Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.FromIndex(26), column3.Cell(4).Style.Fill.BackgroundColor); - Assert.AreEqual(XLColor.FromKnownColor(KnownColor.MediumSeaGreen), + Assert.AreEqual(XLColor.FromColor(Color.MediumSeaGreen), column3.Cell(5).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.FromName("Blue"), column3.Cell(6).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.FromTheme(XLThemeColor.Accent3), column3.Cell(7).Style.Fill.BackgroundColor); @@ -64,7 +64,7 @@ Assert.AreEqual(XLColor.FromArgb(1, 1, 1), row2.Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.FromHtml("#CCCCCC"), row2.Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.FromIndex(26), row2.Cell(4).Style.Fill.BackgroundColor); - Assert.AreEqual(XLColor.FromKnownColor(KnownColor.MediumSeaGreen), row2.Cell(5).Style.Fill.BackgroundColor); + Assert.AreEqual(XLColor.FromColor(Color.MediumSeaGreen), row2.Cell(5).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.FromName("Blue"), row2.Cell(6).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.FromTheme(XLThemeColor.Accent3), row2.Cell(7).Style.Fill.BackgroundColor); @@ -73,7 +73,7 @@ Assert.AreEqual(XLColor.FromArgb(1, 1, 1), row3.Cell(2).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.FromHtml("#CCCCCC"), row3.Cell(3).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.FromIndex(26), row3.Cell(4).Style.Fill.BackgroundColor); - Assert.AreEqual(XLColor.FromKnownColor(KnownColor.MediumSeaGreen), row3.Cell(5).Style.Fill.BackgroundColor); + Assert.AreEqual(XLColor.FromColor(Color.MediumSeaGreen), row3.Cell(5).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.FromName("Blue"), row3.Cell(6).Style.Fill.BackgroundColor); Assert.AreEqual(XLColor.FromTheme(XLThemeColor.Accent3), row3.Cell(7).Style.Fill.BackgroundColor); @@ -100,7 +100,7 @@ Assert.AreEqual(2, ws.ConditionalFormats.Count()); Assert.IsTrue(ws.ConditionalFormats.Single(x => x.Range.RangeAddress.ToStringRelative() == "B1:B3").Values.Any(v => v.Value.Value == "G1" && v.Value.IsFormula)); Assert.IsTrue(ws.ConditionalFormats.Single(x => x.Range.RangeAddress.ToStringRelative() == "C5:C5").Values.Any(v => v.Value.Value == "H5" && v.Value.IsFormula)); - } + } private static void FillRow(IXLRow row1) { @@ -108,7 +108,7 @@ row1.Cell(2).Style.Fill.SetBackgroundColor(XLColor.FromArgb(1, 1, 1)); row1.Cell(3).Style.Fill.SetBackgroundColor(XLColor.FromHtml("#CCCCCC")); row1.Cell(4).Style.Fill.SetBackgroundColor(XLColor.FromIndex(26)); - row1.Cell(5).Style.Fill.SetBackgroundColor(XLColor.FromKnownColor(KnownColor.MediumSeaGreen)); + row1.Cell(5).Style.Fill.SetBackgroundColor(XLColor.FromColor(Color.MediumSeaGreen)); row1.Cell(6).Style.Fill.SetBackgroundColor(XLColor.FromName("Blue")); row1.Cell(7).Style.Fill.SetBackgroundColor(XLColor.FromTheme(XLThemeColor.Accent3)); diff --git a/ClosedXML_Tests/Excel/Ranges/UsedAndUnusedCellsTests.cs b/ClosedXML_Tests/Excel/Ranges/UsedAndUnusedCellsTests.cs index a4442c6..fab9b91 100644 --- a/ClosedXML_Tests/Excel/Ranges/UsedAndUnusedCellsTests.cs +++ b/ClosedXML_Tests/Excel/Ranges/UsedAndUnusedCellsTests.cs @@ -12,7 +12,7 @@ { private XLWorkbook workbook; - [OneTimeSetUp] + [SetUp] public void SetupWorkbook() { workbook = new XLWorkbook(); diff --git a/ClosedXML_Tests/Excel/Saving/SavingTests.cs b/ClosedXML_Tests/Excel/Saving/SavingTests.cs index 7f94697..4b19a6b 100644 --- a/ClosedXML_Tests/Excel/Saving/SavingTests.cs +++ b/ClosedXML_Tests/Excel/Saving/SavingTests.cs @@ -16,6 +16,17 @@ public class SavingTests { [Test] + public void CanSaveEmptyFile() + { + using (var ms = new MemoryStream()) + using (var wb = new XLWorkbook()) + { + wb.AddWorksheet("Sheet1"); + wb.SaveAs(ms); + } + } + + [Test] public void CanSuccessfullySaveFileMultipleTimes() { using (var wb = new XLWorkbook()) diff --git a/ClosedXML_Tests/Excel/Styles/NumberFormatTests.cs b/ClosedXML_Tests/Excel/Styles/NumberFormatTests.cs index ed012b3..76bf394 100644 --- a/ClosedXML_Tests/Excel/Styles/NumberFormatTests.cs +++ b/ClosedXML_Tests/Excel/Styles/NumberFormatTests.cs @@ -27,7 +27,7 @@ Assert.AreEqual("yy-MM-dd", ws.Cell("A5").Style.DateFormat.Format); ws.Row(1).Style.NumberFormat.Format = "yy-MM-dd"; - ws.Cell("A1").InsertData(table.AsEnumerable(), true); + ws.Cell("A1").InsertData(table.Rows, true); Assert.AreEqual("yy-MM-dd", ws.Cell("E1").Style.DateFormat.Format); } } diff --git a/ClosedXML_Tests/Excel/Tables/TablesTests.cs b/ClosedXML_Tests/Excel/Tables/TablesTests.cs index ca50c3f..5df66aa 100644 --- a/ClosedXML_Tests/Excel/Tables/TablesTests.cs +++ b/ClosedXML_Tests/Excel/Tables/TablesTests.cs @@ -44,11 +44,11 @@ using (var wb = new XLWorkbook()) { - wb.AddWorksheet(dt); + wb.AddWorksheet(dt); - using (var ms = new MemoryStream()) - wb.SaveAs(ms, true); - } + using (var ms = new MemoryStream()) + wb.SaveAs(ms, true); + } } [Test] @@ -70,13 +70,13 @@ { using (var wb = new XLWorkbook()) { - IXLWorksheet ws = wb.AddWorksheet("Sheet1"); - ws.FirstCell().SetValue("Title"); - ws.Range("A1").CreateTable(); + IXLWorksheet ws = wb.AddWorksheet("Sheet1"); + ws.FirstCell().SetValue("Title"); + ws.Range("A1").CreateTable(); - using (var ms = new MemoryStream()) - wb.SaveAs(ms, true); - } + using (var ms = new MemoryStream()) + wb.SaveAs(ms, true); + } } [Test] @@ -84,14 +84,14 @@ { using (var wb = new XLWorkbook()) { - IXLWorksheet ws = wb.AddWorksheet("Sheet1"); - ws.FirstCell().SetValue("Title") - .CellBelow().SetValue("X"); - ws.Range("A1").CreateTable(); + IXLWorksheet ws = wb.AddWorksheet("Sheet1"); + ws.FirstCell().SetValue("Title") + .CellBelow().SetValue("X"); + ws.Range("A1").CreateTable(); - Assert.AreEqual(ws.Cell("A2").GetString(), String.Empty); - Assert.AreEqual(ws.Cell("A3").GetString(), "X"); - } + Assert.AreEqual(ws.Cell("A2").GetString(), String.Empty); + Assert.AreEqual(ws.Cell("A3").GetString(), "X"); + } } [Test] @@ -99,16 +99,16 @@ { using (var wb = new XLWorkbook()) { - IXLWorksheet ws = wb.AddWorksheet("Sheet1"); - ws.FirstCell().SetValue("Categories") - .CellBelow().SetValue("A") - .CellBelow().SetValue("B") - .CellBelow().SetValue("C"); + IXLWorksheet ws = wb.AddWorksheet("Sheet1"); + ws.FirstCell().SetValue("Categories") + .CellBelow().SetValue("A") + .CellBelow().SetValue("B") + .CellBelow().SetValue("C"); - IXLTable table = ws.RangeUsed().CreateTable(); - table.InsertColumnsAfter(1); - Assert.AreEqual("Column2", table.HeadersRow().LastCell().GetString()); - } + IXLTable table = ws.RangeUsed().CreateTable(); + table.InsertColumnsAfter(1); + Assert.AreEqual("Column2", table.HeadersRow().LastCell().GetString()); + } } [Test] @@ -116,54 +116,54 @@ { using (var wb = new XLWorkbook()) { - IXLWorksheet ws = wb.AddWorksheet("Sheet1"); - string columnName = "Line1" + Environment.NewLine + "Line2"; - ws.FirstCell().SetValue(columnName) - .CellBelow().SetValue("A"); - ws.RangeUsed().CreateTable(); - using (var ms = new MemoryStream()) - { - wb.SaveAs(ms, true); - var wb2 = new XLWorkbook(ms); - IXLWorksheet ws2 = wb2.Worksheet(1); - IXLTable table2 = ws2.Table(0); - string fieldName = table2.Field(0).Name; - Assert.AreEqual("Line1\nLine2", fieldName); - } + IXLWorksheet ws = wb.AddWorksheet("Sheet1"); + string columnName = "Line1" + Environment.NewLine + "Line2"; + ws.FirstCell().SetValue(columnName) + .CellBelow().SetValue("A"); + ws.RangeUsed().CreateTable(); + using (var ms = new MemoryStream()) + { + wb.SaveAs(ms, true); + var wb2 = new XLWorkbook(ms); + IXLWorksheet ws2 = wb2.Worksheet(1); + IXLTable table2 = ws2.Table(0); + string fieldName = table2.Field(0).Name; + Assert.AreEqual("Line1\nLine2", fieldName); } } + } [Test] public void SavingLoadingTableWithNewLineInHeader2() { using (var wb = new XLWorkbook()) { - IXLWorksheet ws = wb.Worksheets.Add("Test"); + IXLWorksheet ws = wb.Worksheets.Add("Test"); - var dt = new DataTable(); - string columnName = "Line1" + Environment.NewLine + "Line2"; - dt.Columns.Add(columnName); + var dt = new DataTable(); + string columnName = "Line1" + Environment.NewLine + "Line2"; + dt.Columns.Add(columnName); - DataRow dr = dt.NewRow(); - dr[columnName] = "some text"; - dt.Rows.Add(dr); + DataRow dr = dt.NewRow(); + dr[columnName] = "some text"; + dt.Rows.Add(dr); ws.Cell(1, 1).InsertTable(dt); - IXLTable table1 = ws.Table(0); - string fieldName1 = table1.Field(0).Name; - Assert.AreEqual(columnName, fieldName1); + IXLTable table1 = ws.Table(0); + string fieldName1 = table1.Field(0).Name; + Assert.AreEqual(columnName, fieldName1); - using (var ms = new MemoryStream()) - { - wb.SaveAs(ms, true); - var wb2 = new XLWorkbook(ms); - IXLWorksheet ws2 = wb2.Worksheet(1); - IXLTable table2 = ws2.Table(0); - string fieldName2 = table2.Field(0).Name; - Assert.AreEqual("Line1\nLine2", fieldName2); - } + using (var ms = new MemoryStream()) + { + wb.SaveAs(ms, true); + var wb2 = new XLWorkbook(ms); + IXLWorksheet ws2 = wb2.Worksheet(1); + IXLTable table2 = ws2.Table(0); + string fieldName2 = table2.Field(0).Name; + Assert.AreEqual("Line1\nLine2", fieldName2); } } + } [Test] public void TableCreatedFromEmptyDataTable() @@ -174,10 +174,10 @@ using (var wb = new XLWorkbook()) { - IXLWorksheet ws = wb.AddWorksheet("Sheet1"); - ws.FirstCell().InsertTable(dt); - Assert.AreEqual(2, ws.Tables.First().ColumnCount()); - } + IXLWorksheet ws = wb.AddWorksheet("Sheet1"); + ws.FirstCell().InsertTable(dt); + Assert.AreEqual(2, ws.Tables.First().ColumnCount()); + } } [Test] @@ -187,10 +187,10 @@ using (var wb = new XLWorkbook()) { - IXLWorksheet ws = wb.AddWorksheet("Sheet1"); - ws.FirstCell().InsertTable(l); - Assert.AreEqual(1, ws.Tables.First().ColumnCount()); - } + IXLWorksheet ws = wb.AddWorksheet("Sheet1"); + ws.FirstCell().InsertTable(l); + Assert.AreEqual(1, ws.Tables.First().ColumnCount()); + } } [Test] @@ -200,10 +200,10 @@ using (var wb = new XLWorkbook()) { - IXLWorksheet ws = wb.AddWorksheet("Sheet1"); - ws.FirstCell().InsertTable(l); - Assert.AreEqual(2, ws.Tables.First().ColumnCount()); - } + IXLWorksheet ws = wb.AddWorksheet("Sheet1"); + ws.FirstCell().InsertTable(l); + Assert.AreEqual(2, ws.Tables.First().ColumnCount()); + } } [Test] @@ -217,14 +217,14 @@ using (var wb = new XLWorkbook()) { - IXLWorksheet ws = wb.AddWorksheet("Sheet1"); - ws.FirstCell().InsertTable(l); - Assert.AreEqual(4, ws.Tables.First().ColumnCount()); - Assert.AreEqual("FirstColumn", ws.FirstCell().Value); - Assert.AreEqual("SecondColumn", ws.FirstCell().CellRight().Value); - Assert.AreEqual("SomeFieldNotProperty", ws.FirstCell().CellRight().CellRight().Value); - Assert.AreEqual("UnOrderedColumn", ws.FirstCell().CellRight().CellRight().CellRight().Value); - } + IXLWorksheet ws = wb.AddWorksheet("Sheet1"); + ws.FirstCell().InsertTable(l); + Assert.AreEqual(4, ws.Tables.First().ColumnCount()); + Assert.AreEqual("FirstColumn", ws.FirstCell().Value); + Assert.AreEqual("SecondColumn", ws.FirstCell().CellRight().Value); + Assert.AreEqual("SomeFieldNotProperty", ws.FirstCell().CellRight().CellRight().Value); + Assert.AreEqual("UnOrderedColumn", ws.FirstCell().CellRight().CellRight().CellRight().Value); + } } [Test] @@ -232,24 +232,24 @@ { using (var wb = new XLWorkbook()) { - IXLWorksheet ws = wb.AddWorksheet("Sheet1"); - ws.FirstCell().SetValue("Value"); + IXLWorksheet ws = wb.AddWorksheet("Sheet1"); + ws.FirstCell().SetValue("Value"); - IXLTable table = ws.Range("A1:A2").CreateTable(); - table.SetShowTotalsRow() - .Field(0).TotalsRowFunction = XLTotalsRowFunction.Sum; + IXLTable table = ws.Range("A1:A2").CreateTable(); + table.SetShowTotalsRow() + .Field(0).TotalsRowFunction = XLTotalsRowFunction.Sum; - IXLTableRow row = table.DataRange.FirstRow(); - row.Field("Value").Value = 3; - row = table.DataRange.InsertRowsAbove(1).First(); - row.Field("Value").Value = 2; - row = table.DataRange.InsertRowsAbove(1).First(); - row.Field("Value").Value = 1; + IXLTableRow row = table.DataRange.FirstRow(); + row.Field("Value").Value = 3; + row = table.DataRange.InsertRowsAbove(1).First(); + row.Field("Value").Value = 2; + row = table.DataRange.InsertRowsAbove(1).First(); + row.Field("Value").Value = 1; - Assert.AreEqual(1, ws.Cell(2, 1).GetDouble()); - Assert.AreEqual(2, ws.Cell(3, 1).GetDouble()); - Assert.AreEqual(3, ws.Cell(4, 1).GetDouble()); - } + Assert.AreEqual(1, ws.Cell(2, 1).GetDouble()); + Assert.AreEqual(2, ws.Cell(3, 1).GetDouble()); + Assert.AreEqual(3, ws.Cell(4, 1).GetDouble()); + } } [Test] @@ -257,24 +257,24 @@ { using (var wb = new XLWorkbook()) { - IXLWorksheet ws = wb.AddWorksheet("Sheet1"); - ws.FirstCell().SetValue("Value"); + IXLWorksheet ws = wb.AddWorksheet("Sheet1"); + ws.FirstCell().SetValue("Value"); - IXLTable table = ws.Range("A1:A2").CreateTable(); - table.SetShowTotalsRow() - .Field(0).TotalsRowFunction = XLTotalsRowFunction.Sum; + IXLTable table = ws.Range("A1:A2").CreateTable(); + table.SetShowTotalsRow() + .Field(0).TotalsRowFunction = XLTotalsRowFunction.Sum; - IXLTableRow row = table.DataRange.FirstRow(); - row.Field("Value").Value = 3; - row = row.InsertRowsAbove(1).First(); - row.Field("Value").Value = 2; - row = row.InsertRowsAbove(1).First(); - row.Field("Value").Value = 1; + IXLTableRow row = table.DataRange.FirstRow(); + row.Field("Value").Value = 3; + row = row.InsertRowsAbove(1).First(); + row.Field("Value").Value = 2; + row = row.InsertRowsAbove(1).First(); + row.Field("Value").Value = 1; - Assert.AreEqual(1, ws.Cell(2, 1).GetDouble()); - Assert.AreEqual(2, ws.Cell(3, 1).GetDouble()); - Assert.AreEqual(3, ws.Cell(4, 1).GetDouble()); - } + Assert.AreEqual(1, ws.Cell(2, 1).GetDouble()); + Assert.AreEqual(2, ws.Cell(3, 1).GetDouble()); + Assert.AreEqual(3, ws.Cell(4, 1).GetDouble()); + } } [Test] @@ -282,24 +282,24 @@ { using (var wb = new XLWorkbook()) { - IXLWorksheet ws = wb.AddWorksheet("Sheet1"); - ws.FirstCell().SetValue("Value"); + IXLWorksheet ws = wb.AddWorksheet("Sheet1"); + ws.FirstCell().SetValue("Value"); - IXLTable table = ws.Range("A1:A2").CreateTable(); - table.SetShowTotalsRow() - .Field(0).TotalsRowFunction = XLTotalsRowFunction.Sum; + IXLTable table = ws.Range("A1:A2").CreateTable(); + table.SetShowTotalsRow() + .Field(0).TotalsRowFunction = XLTotalsRowFunction.Sum; - IXLTableRow row = table.DataRange.FirstRow(); - row.Field("Value").Value = 1; - row = table.DataRange.InsertRowsBelow(1).First(); - row.Field("Value").Value = 2; - row = table.DataRange.InsertRowsBelow(1).First(); - row.Field("Value").Value = 3; + IXLTableRow row = table.DataRange.FirstRow(); + row.Field("Value").Value = 1; + row = table.DataRange.InsertRowsBelow(1).First(); + row.Field("Value").Value = 2; + row = table.DataRange.InsertRowsBelow(1).First(); + row.Field("Value").Value = 3; - Assert.AreEqual(1, ws.Cell(2, 1).GetDouble()); - Assert.AreEqual(2, ws.Cell(3, 1).GetDouble()); - Assert.AreEqual(3, ws.Cell(4, 1).GetDouble()); - } + Assert.AreEqual(1, ws.Cell(2, 1).GetDouble()); + Assert.AreEqual(2, ws.Cell(3, 1).GetDouble()); + Assert.AreEqual(3, ws.Cell(4, 1).GetDouble()); + } } [Test] @@ -307,24 +307,24 @@ { using (var wb = new XLWorkbook()) { - IXLWorksheet ws = wb.AddWorksheet("Sheet1"); - ws.FirstCell().SetValue("Value"); + IXLWorksheet ws = wb.AddWorksheet("Sheet1"); + ws.FirstCell().SetValue("Value"); - IXLTable table = ws.Range("A1:A2").CreateTable(); - table.SetShowTotalsRow() - .Field(0).TotalsRowFunction = XLTotalsRowFunction.Sum; + IXLTable table = ws.Range("A1:A2").CreateTable(); + table.SetShowTotalsRow() + .Field(0).TotalsRowFunction = XLTotalsRowFunction.Sum; - IXLTableRow row = table.DataRange.FirstRow(); - row.Field("Value").Value = 1; - row = row.InsertRowsBelow(1).First(); - row.Field("Value").Value = 2; - row = row.InsertRowsBelow(1).First(); - row.Field("Value").Value = 3; + IXLTableRow row = table.DataRange.FirstRow(); + row.Field("Value").Value = 1; + row = row.InsertRowsBelow(1).First(); + row.Field("Value").Value = 2; + row = row.InsertRowsBelow(1).First(); + row.Field("Value").Value = 3; - Assert.AreEqual(1, ws.Cell(2, 1).GetDouble()); - Assert.AreEqual(2, ws.Cell(3, 1).GetDouble()); - Assert.AreEqual(3, ws.Cell(4, 1).GetDouble()); - } + Assert.AreEqual(1, ws.Cell(2, 1).GetDouble()); + Assert.AreEqual(2, ws.Cell(3, 1).GetDouble()); + Assert.AreEqual(3, ws.Cell(4, 1).GetDouble()); + } } [Test] @@ -332,46 +332,46 @@ { using (var wb = new XLWorkbook()) { - IXLWorksheet ws = wb.AddWorksheet("Sheet1"); - ws.FirstCell().SetValue("Categories") - .CellBelow().SetValue("A") - .CellBelow().SetValue("B") - .CellBelow().SetValue("C"); + IXLWorksheet ws = wb.AddWorksheet("Sheet1"); + ws.FirstCell().SetValue("Categories") + .CellBelow().SetValue("A") + .CellBelow().SetValue("B") + .CellBelow().SetValue("C"); - IXLTable table = ws.RangeUsed().CreateTable(); + IXLTable table = ws.RangeUsed().CreateTable(); - Assert.AreEqual("Categories", table.Fields.First().Name); + Assert.AreEqual("Categories", table.Fields.First().Name); - table.SetShowHeaderRow(false); + table.SetShowHeaderRow(false); - Assert.AreEqual("Categories", table.Fields.First().Name); + Assert.AreEqual("Categories", table.Fields.First().Name); - Assert.IsTrue(ws.Cell(1, 1).IsEmpty(true)); - Assert.AreEqual(null, table.HeadersRow()); - Assert.AreEqual("A", table.DataRange.FirstRow().Field("Categories").GetString()); - Assert.AreEqual("C", table.DataRange.LastRow().Field("Categories").GetString()); - Assert.AreEqual("A", table.DataRange.FirstCell().GetString()); - Assert.AreEqual("C", table.DataRange.LastCell().GetString()); + Assert.IsTrue(ws.Cell(1, 1).IsEmpty(true)); + Assert.AreEqual(null, table.HeadersRow()); + Assert.AreEqual("A", table.DataRange.FirstRow().Field("Categories").GetString()); + Assert.AreEqual("C", table.DataRange.LastRow().Field("Categories").GetString()); + Assert.AreEqual("A", table.DataRange.FirstCell().GetString()); + Assert.AreEqual("C", table.DataRange.LastCell().GetString()); - table.SetShowHeaderRow(); - IXLRangeRow headerRow = table.HeadersRow(); - Assert.AreNotEqual(null, headerRow); - Assert.AreEqual("Categories", headerRow.Cell(1).GetString()); + table.SetShowHeaderRow(); + IXLRangeRow headerRow = table.HeadersRow(); + Assert.AreNotEqual(null, headerRow); + Assert.AreEqual("Categories", headerRow.Cell(1).GetString()); - table.SetShowHeaderRow(false); + table.SetShowHeaderRow(false); - ws.FirstCell().SetValue("x"); + ws.FirstCell().SetValue("x"); - table.SetShowHeaderRow(); + table.SetShowHeaderRow(); - Assert.AreEqual("x", ws.FirstCell().GetString()); - Assert.AreEqual("Categories", ws.Cell("A2").GetString()); - Assert.AreNotEqual(null, headerRow); - Assert.AreEqual("A", table.DataRange.FirstRow().Field("Categories").GetString()); - Assert.AreEqual("C", table.DataRange.LastRow().Field("Categories").GetString()); - Assert.AreEqual("A", table.DataRange.FirstCell().GetString()); - Assert.AreEqual("C", table.DataRange.LastCell().GetString()); - } + Assert.AreEqual("x", ws.FirstCell().GetString()); + Assert.AreEqual("Categories", ws.Cell("A2").GetString()); + Assert.AreNotEqual(null, headerRow); + Assert.AreEqual("A", table.DataRange.FirstRow().Field("Categories").GetString()); + Assert.AreEqual("C", table.DataRange.LastRow().Field("Categories").GetString()); + Assert.AreEqual("A", table.DataRange.FirstCell().GetString()); + Assert.AreEqual("C", table.DataRange.LastCell().GetString()); + } } [Test] @@ -379,40 +379,40 @@ { using (var wb = new XLWorkbook()) { - var ws = wb.AddWorksheet("Sheet"); - ws.Cell("A1").SetValue("FName") - .CellBelow().SetValue("John"); + var ws = wb.AddWorksheet("Sheet"); + ws.Cell("A1").SetValue("FName") + .CellBelow().SetValue("John"); - ws.Cell("B1").SetValue("LName") - .CellBelow().SetValue("Doe"); + ws.Cell("B1").SetValue("LName") + .CellBelow().SetValue("Doe"); - var tbl = ws.RangeUsed().CreateTable(); - var nameBefore = tbl.Field(tbl.Fields.Last().Index).Name; - tbl.Field(tbl.Fields.Last().Index).Name = "LastName"; - var nameAfter = tbl.Field(tbl.Fields.Last().Index).Name; + var tbl = ws.RangeUsed().CreateTable(); + var nameBefore = tbl.Field(tbl.Fields.Last().Index).Name; + tbl.Field(tbl.Fields.Last().Index).Name = "LastName"; + var nameAfter = tbl.Field(tbl.Fields.Last().Index).Name; - var cellValue = ws.Cell("B1").GetString(); + var cellValue = ws.Cell("B1").GetString(); - Assert.AreEqual("LName", nameBefore); - Assert.AreEqual("LastName", nameAfter); - Assert.AreEqual("LastName", cellValue); + Assert.AreEqual("LName", nameBefore); + Assert.AreEqual("LastName", nameAfter); + Assert.AreEqual("LastName", cellValue); - tbl.ShowHeaderRow = false; - tbl.Field(tbl.Fields.Last().Index).Name = "LastNameChanged"; - nameAfter = tbl.Field(tbl.Fields.Last().Index).Name; - Assert.AreEqual("LastNameChanged", nameAfter); + tbl.ShowHeaderRow = false; + tbl.Field(tbl.Fields.Last().Index).Name = "LastNameChanged"; + nameAfter = tbl.Field(tbl.Fields.Last().Index).Name; + Assert.AreEqual("LastNameChanged", nameAfter); - tbl.SetShowHeaderRow(true); - nameAfter = tbl.Cell("B1").Value.ToString(); - Assert.AreEqual("LastNameChanged", nameAfter); + tbl.SetShowHeaderRow(true); + nameAfter = tbl.Cell("B1").Value.ToString(); + Assert.AreEqual("LastNameChanged", nameAfter); var field = tbl.Field("LastNameChanged"); Assert.AreEqual("LastNameChanged", field.Name); tbl.Cell(1, 1).Value = "FirstName"; Assert.AreEqual("FirstName", tbl.Field(0).Name); - } } + } [Test] public void CanDeleteTableColumn() @@ -437,7 +437,7 @@ Assert.AreEqual("UnOrderedColumn", table.Fields.Last().Name); Assert.AreEqual(2, table.Fields.Last().Index); - } +} } [Test] @@ -510,8 +510,8 @@ IXLWorksheet ws = wb.AddWorksheet("Sheet1"); ws.FirstCell().InsertTable(dt, true); Assert.Throws(() => ws.FirstCell().CellRight().InsertTable(dt, true)); - } - } + } +} [Test] public void OverwritingTableTotalsRow() diff --git a/ClosedXML_Tests/ExcelDocsComparerTests.cs b/ClosedXML_Tests/ExcelDocsComparerTests.cs index ac2fa36..42677eb 100644 --- a/ClosedXML_Tests/ExcelDocsComparerTests.cs +++ b/ClosedXML_Tests/ExcelDocsComparerTests.cs @@ -1,6 +1,6 @@ -using System.IO; using ClosedXML_Examples; using NUnit.Framework; +using System.IO; namespace ClosedXML_Tests { @@ -17,7 +17,7 @@ new BasicTable().Create(left); new BasicTable().Create(right); string message; - Assert.IsTrue(ExcelDocsComparer.Compare(left, right, TestHelper.IsRunningOnUnix, out message)); + Assert.IsTrue(ExcelDocsComparer.Compare(left, right, out message)); } finally { @@ -43,7 +43,7 @@ new HelloWorld().Create(right); string message; - Assert.IsFalse(ExcelDocsComparer.Compare(left, right, TestHelper.IsRunningOnUnix, out message)); + Assert.IsFalse(ExcelDocsComparer.Compare(left, right, out message)); } finally { @@ -58,4 +58,4 @@ } } } -} \ No newline at end of file +} diff --git a/ClosedXML_Tests/OleDb/OleDbTests.cs b/ClosedXML_Tests/OleDb/OleDbTests.cs index 2aa897c..b7cd054 100644 --- a/ClosedXML_Tests/OleDb/OleDbTests.cs +++ b/ClosedXML_Tests/OleDb/OleDbTests.cs @@ -1,4 +1,5 @@ -using ClosedXML.Excel; +#if !APPVEYOR && _NETFRAMEWORK_ +using ClosedXML.Excel; using ClosedXML_Tests.Utils; using NUnit.Framework; using System; @@ -13,7 +14,6 @@ [TestFixture] public class OleDbTests { -#if !APPVEYOR [Test] public void TestOleDbValues() { @@ -78,7 +78,6 @@ } } } -#endif private string CreateTestFile() { @@ -118,3 +117,4 @@ } } } +#endif diff --git a/ClosedXML_Tests/OpenXMLTests.cs b/ClosedXML_Tests/OpenXMLTests.cs new file mode 100644 index 0000000..c0d0ddf --- /dev/null +++ b/ClosedXML_Tests/OpenXMLTests.cs @@ -0,0 +1,30 @@ +using DocumentFormat.OpenXml.Packaging; +using NUnit.Framework; +using System.IO; + +namespace ClosedXML_Tests +{ + [TestFixture] + public class OpenXMLTests + { + [Test] + [Ignore("Workaround has been included in ClosedXML")] + public static void SetPackagePropertiesEntryToNullWithOpenXml() + { + // Fixed in .NET Standard 2.1 + // See: + // https://github.com/OfficeDev/Open-XML-SDK/issues/235 + // https://github.com/dotnet/corefx/issues/23795 + using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Examples\PivotTables\PivotTables.xlsx"))) + using (var ms = new MemoryStream()) + { + stream.CopyTo(ms); + + using (var document = SpreadsheetDocument.Open(ms, true)) + { + document.PackageProperties.Creator = null; + } + } + } + } +} diff --git a/ClosedXML_Tests/Properties/AssemblyInfo.cs b/ClosedXML_Tests/Properties/AssemblyInfo.cs deleted file mode 100644 index bfb414e..0000000 --- a/ClosedXML_Tests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System.Reflection; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. - -[assembly: AssemblyTitle("ClosedXML_Tests")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("ClosedXML_Tests")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. - -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM - -[assembly: Guid("a16b867e-6b00-4ccc-a368-c9f9b14e0e6a")] - diff --git a/ClosedXML_Tests/Resource/Examples/Styles/UsingColors.xlsx b/ClosedXML_Tests/Resource/Examples/Styles/UsingColors.xlsx index 2ada7d9..2d49b85 100644 --- a/ClosedXML_Tests/Resource/Examples/Styles/UsingColors.xlsx +++ b/ClosedXML_Tests/Resource/Examples/Styles/UsingColors.xlsx Binary files differ diff --git a/ClosedXML_Tests/Resource/StyleReferenceFiles/ConditionalFormattingOrder/ConditionalFormattingOrder.xlsx b/ClosedXML_Tests/Resource/StyleReferenceFiles/ConditionalFormattingOrder/ConditionalFormattingOrder.xlsx index 5f27c54..ed07359 100644 --- a/ClosedXML_Tests/Resource/StyleReferenceFiles/ConditionalFormattingOrder/ConditionalFormattingOrder.xlsx +++ b/ClosedXML_Tests/Resource/StyleReferenceFiles/ConditionalFormattingOrder/ConditionalFormattingOrder.xlsx Binary files differ diff --git a/ClosedXML_Tests/Resource/StyleReferenceFiles/TransparentBackgroundFill/TransparentBackgroundFill.xlsx b/ClosedXML_Tests/Resource/StyleReferenceFiles/TransparentBackgroundFill/TransparentBackgroundFill.xlsx index 3a12637..bccd5b2 100644 --- a/ClosedXML_Tests/Resource/StyleReferenceFiles/TransparentBackgroundFill/TransparentBackgroundFill.xlsx +++ b/ClosedXML_Tests/Resource/StyleReferenceFiles/TransparentBackgroundFill/TransparentBackgroundFill.xlsx Binary files differ diff --git a/ClosedXML_Tests/TestHelper.cs b/ClosedXML_Tests/TestHelper.cs index 5c1acf8..1887cd5 100644 --- a/ClosedXML_Tests/TestHelper.cs +++ b/ClosedXML_Tests/TestHelper.cs @@ -43,6 +43,8 @@ // the columns widths after AdjustToContents() will // cause the tests to fail. // Therefore we ignore the width attribute when running on Unix + public static bool StripColumnWidths { get { return IsRunningOnUnix; } } + public static bool IsRunningOnUnix { get @@ -83,7 +85,7 @@ using (var streamActual = File.OpenRead(filePath2)) { string message; - var success = ExcelDocsComparer.Compare(streamActual, streamExpected, TestHelper.IsRunningOnUnix, out message); + var success = ExcelDocsComparer.Compare(streamActual, streamExpected, out message); var formattedMessage = String.Format( "Actual file '{0}' is different than the expected file '{1}'. The difference is: '{2}'", @@ -108,7 +110,6 @@ fileName += ActualTestResultPostFix; fileName = Path.ChangeExtension(fileName, extension); - filePath1 = Path.Combine(directory, "z" + fileName); var filePath2 = Path.Combine(directory, fileName); using (var wb = workbookGenerator.Invoke()) @@ -121,7 +122,7 @@ using (var streamActual = File.OpenRead(filePath2)) { string message; - var success = ExcelDocsComparer.Compare(streamActual, streamExpected, TestHelper.IsRunningOnUnix, out message); + var success = ExcelDocsComparer.Compare(streamActual, streamExpected, out message); var formattedMessage = String.Format( "Actual file '{0}' is different than the expected file '{1}'. The difference is: '{2}'", diff --git a/ClosedXML_Tests/Utils/ExcelDocsComparer.cs b/ClosedXML_Tests/Utils/ExcelDocsComparer.cs index 2ad4ab2..9c35602 100644 --- a/ClosedXML_Tests/Utils/ExcelDocsComparer.cs +++ b/ClosedXML_Tests/Utils/ExcelDocsComparer.cs @@ -6,25 +6,21 @@ { internal static class ExcelDocsComparer { - public static bool Compare(string left, string right, bool stripColumnWidths, out string message) + public static bool Compare(string left, string right, out string message) { using (FileStream leftStream = File.OpenRead(left)) + using (FileStream rightStream = File.OpenRead(right)) { - using (FileStream rightStream = File.OpenRead(right)) - { - return Compare(leftStream, rightStream, stripColumnWidths, out message); - } + return Compare(leftStream, rightStream, out message); } } - public static bool Compare(Stream left, Stream right, bool stripColumnWidths, out string message) + public static bool Compare(Stream left, Stream right, out string message) { - using (Package leftPackage = Package.Open(left)) + using (Package leftPackage = Package.Open(left, FileMode.Open, FileAccess.Read)) + using (Package rightPackage = Package.Open(right, FileMode.Open, FileAccess.Read)) { - using (Package rightPackage = Package.Open(right)) - { - return PackageHelper.Compare(leftPackage, rightPackage, false, ExcludeMethod, stripColumnWidths, out message); - } + return PackageHelper.Compare(leftPackage, rightPackage, false, ExcludeMethod, out message); } } @@ -39,4 +35,4 @@ return false; } } -} \ No newline at end of file +} diff --git a/ClosedXML_Tests/Utils/PackageHelper.cs b/ClosedXML_Tests/Utils/PackageHelper.cs index 60bc482..f4f43cd 100644 --- a/ClosedXML_Tests/Utils/PackageHelper.cs +++ b/ClosedXML_Tests/Utils/PackageHelper.cs @@ -273,9 +273,9 @@ /// /// /// - public static bool Compare(Package left, Package right, bool compareToFirstDifference, bool stripColumnWidths, out string message) + public static bool Compare(Package left, Package right, bool compareToFirstDifference, out string message) { - return Compare(left, right, compareToFirstDifference, null, stripColumnWidths, out message); + return Compare(left, right, compareToFirstDifference, null, out message); } /// @@ -288,7 +288,7 @@ /// /// public static bool Compare(Package left, Package right, bool compareToFirstDifference, - Func excludeMethod, bool stripColumnWidths, out string message) + Func excludeMethod, out string message) { #region Check @@ -346,15 +346,23 @@ } var leftPart = left.GetPart(pair.Uri); var rightPart = right.GetPart(pair.Uri); - using (Stream oneStream = leftPart.GetStream(FileMode.Open, FileAccess.Read)) - using (Stream otherStream = rightPart.GetStream(FileMode.Open, FileAccess.Read)) + using (Stream leftPackagePartStream = leftPart.GetStream(FileMode.Open, FileAccess.Read)) + using (Stream rightPackagePartStream = rightPart.GetStream(FileMode.Open, FileAccess.Read)) + using (var leftMemoryStream = new MemoryStream()) + using (var rightMemoryStream = new MemoryStream()) { - bool stripColumnWidthsFromSheet = stripColumnWidths && + leftPackagePartStream.CopyTo(leftMemoryStream); + rightPackagePartStream.CopyTo(rightMemoryStream); + + leftMemoryStream.Seek(0, SeekOrigin.Begin); + rightMemoryStream.Seek(0, SeekOrigin.Begin); + + bool stripColumnWidthsFromSheet = TestHelper.StripColumnWidths && leftPart.ContentType == @"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" && rightPart.ContentType == @"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"; - var tuple1 = new Tuple(pair.Uri, oneStream); - var tuple2 = new Tuple(pair.Uri, otherStream); + var tuple1 = new Tuple(pair.Uri, leftMemoryStream); + var tuple2 = new Tuple(pair.Uri, rightMemoryStream); if (!StreamHelper.Compare(tuple1, tuple2, stripColumnWidthsFromSheet)) { diff --git a/ClosedXML_Tests/Utils/StreamHelper.cs b/ClosedXML_Tests/Utils/StreamHelper.cs index bf89911..59ef12c 100644 --- a/ClosedXML_Tests/Utils/StreamHelper.cs +++ b/ClosedXML_Tests/Utils/StreamHelper.cs @@ -147,6 +147,9 @@ foreach (var pair in uriSpecificIgnores.Where(p => p.Key.Equals(uri.OriginalString))) s = pair.Value.Replace(s, ""); + // Collapse empty xml elements + s = emptyXmlElementRegex.Replace(s, "<$1 />"); + if (ignoreColumnWidths) s = RemoveColumnWidths(s); @@ -162,6 +165,7 @@ new KeyValuePair("/docProps/core.xml", new Regex(@"", RegexOptions.Compiled)) }; + private static Regex emptyXmlElementRegex = new Regex(@"<([\w:]+)><\/\1>", RegexOptions.Compiled); private static Regex columnRegex = new Regex("", RegexOptions.Compiled); private static Regex widthRegex = new Regex("width=\"\\d+(\\.\\d+)?\"\\s+", RegexOptions.Compiled); diff --git a/ClosedXML_Tests/packages.config b/ClosedXML_Tests/packages.config deleted file mode 100644 index 5e0ab7c..0000000 --- a/ClosedXML_Tests/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/appveyor.yml b/appveyor.yml index db11140..8784d50 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,18 +1,17 @@ version: 0.92.{build} -branches: - # whitelist - only: - - develop - # blacklist - except: - - gh-pages -# Build worker image (VM template) -image: Visual Studio 2015 +os: Visual Studio 2017 +image: Visual Studio 2017 + environment: AppVeyor: APPVEYOR -# enable patching of AssemblyInfo.* files +branches: + only: + - develop + except: + - gh-pages + assembly_info: patch: true file: AssemblyInfo.* @@ -20,24 +19,27 @@ assembly_file_version: "{version}" assembly_informational_version: "{version}" -#---------------------------------# -# build configuration # -#---------------------------------# - -# build platform, i.e. x86, x64, Any CPU. This setting is optional. -platform: Any CPU - -build: - parallel: true # enable MSBuild parallel builds - project: ClosedXML.sln # path to Visual Studio solution or project - verbosity: minimal - +# platform: Any CPU configuration : Release -#Restore +build: + parallel: true + project: ClosedXML.sln + verbosity: minimal + before_build: + - ps: if (Test-Path 'C:\Tools\NuGet43') { $nugetDir = 'C:\Tools\NuGet43' } else { $nugetDir = 'C:\Tools\NuGet' } + - ps: (New-Object Net.WebClient).DownloadFile('https://dist.nuget.org/win-x86-commandline/v4.3.0/nuget.exe', "$nugetDir\NuGet.exe") + - cmd: nuget update -self - nuget restore artifacts: - - path: ClosedXML/bin/Release/ClosedXML.dll - - path: ClosedXML/bin/Release/ClosedXML.xml + - path: ClosedXML/bin/Release/netstandard2.0/ClosedXML.dll + - path: ClosedXML/bin/Release/net40/ClosedXML.dll + - path: ClosedXML/bin/Release/net46/ClosedXML.dll + +test: + assemblies: + - ClosedXML_Tests/bin/Release/netcoreapp2.0/ClosedXML_Tests.dll + - ClosedXML_Tests/bin/Release/net40/ClosedXML_Tests.dll + - ClosedXML_Tests/bin/Release/net46/ClosedXML_Tests.dll