public IExcelConfiguration HasSheetConfiguration(int sheetIndex, string sheetName, int startRowIndex, bool enableAutoColumnWidth, int?endRowIndex = null) { if (sheetIndex >= 0) { if (SheetSettings.TryGetValue(sheetIndex, out var sheetSetting)) { sheetSetting.SheetName = sheetName; sheetSetting.StartRowIndex = startRowIndex; sheetSetting.AutoColumnWidthEnabled = enableAutoColumnWidth; sheetSetting.EndRowIndex = endRowIndex; } else { SheetSettings[sheetIndex] = new SheetSetting() { SheetIndex = sheetIndex, SheetName = sheetName, StartRowIndex = startRowIndex, AutoColumnWidthEnabled = enableAutoColumnWidth, EndRowIndex = endRowIndex }; } } return(this); }
public void TestNew() { SheetSettings doc = new SheetSettings(); Assert.NotNull(doc); //Assert.AreEqual("sansserif", doc.DiagnosticRulesFont.Family); //doc.DiagnosticRulesFont.Family = "Cascadia Code"; //Assert.AreEqual("Cascadia Code", doc.DiagnosticRulesFont.Family); }
/// <summary> Reads in the contents of this sheet</summary> internal void readSheet() { // If this sheet contains only a chart, then set everything to // empty and do not bother parsing the sheet // Thanks to steve.brophy for spotting this if (!sheetBof.isWorksheet()) { numRows = 0; numCols = 0; cells = new Cell[0][]; for (int i = 0; i < 0; i++) { cells[i] = new Cell[0]; } // return; } SheetReader reader = new SheetReader(excelFile, sharedStrings, formattingRecords, sheetBof, workbookBof, nineteenFour, workbook, startPosition, this); reader.read(); // Take stuff that was read in numRows = reader.NumRows; numCols = reader.NumCols; cells = reader.Cells; rowProperties = reader.RowProperties; columnInfosArray = reader.ColumnInfosArray; hyperlinks = reader.Hyperlinks; charts = reader.Charts; drawings = reader.Drawings; mergedCells = reader.MergedCells; settings = reader.Settings; settings.Hidden = hidden; rowBreaks = reader.RowBreaks; workspaceOptions = reader.WorkspaceOptions; plsRecord = reader.PLS; reader = null; if (!workbookSettings.GCDisabled) { System.GC.Collect(); } if (columnInfosArray.Count > 0) { ColumnInfoRecord cir = (ColumnInfoRecord)columnInfosArray[columnInfosArray.Count - 1]; columnInfos = new ColumnInfoRecord[cir.EndColumn + 1]; } else { columnInfos = new ColumnInfoRecord[0]; } }
/** * Constructor */ public Window2Record(SheetSettings settings) : base(Type.WINDOW2) { int options = 0; options |= 0x0; // display formula values, not formulas if (settings.getShowGridLines()) { options |= 0x02; } options |= 0x04; // display row and column headings options |= 0x0; // panes should be not frozen if (settings.getDisplayZeroValues()) { options |= 0x10; } options |= 0x20; // default header options |= 0x80; // display outline symbols // Handle the freeze panes if (settings.getHorizontalFreeze() != 0 || settings.getVerticalFreeze() != 0) { options |= 0x08; options |= 0x100; } // Handle the selected flag if (settings.isSelected()) { options |= 0x600; } // Handle the view mode if (settings.getPageBreakPreviewMode()) { options |= 0x800; } // hard code the data in for now data = new byte[18]; IntegerHelper.getTwoBytes(options, data, 0); IntegerHelper.getTwoBytes(0x40, data, 6); // grid line colour IntegerHelper.getTwoBytes(settings.getPageBreakPreviewMagnification(), data, 10); IntegerHelper.getTwoBytes(settings.getNormalMagnification(), data, 12); }
public void TestSerializeToFile() { SheetSettings doc = new SheetSettings(); // Use the name of the test file as the Document.File property string file = "WinPrint.Test.New.json"; Assert.Equal("WinPrint.Test.New.json", file); string jsonString = JsonSerializer.Serialize(doc, jsonOptions);; JsonWriterOptions writerOptions = new JsonWriterOptions { Indented = true }; JsonDocumentOptions documentOptions = new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip }; // Use the name of the test file as the Document.File property using (FileStream fs = File.Create(file)) using (Utf8JsonWriter writer = new Utf8JsonWriter(fs, options: writerOptions)) using (JsonDocument document = JsonDocument.Parse(jsonString, documentOptions)) { JsonElement root = document.RootElement; if (root.ValueKind == JsonValueKind.Object) { writer.WriteStartObject(); } else { return; } foreach (JsonProperty property in root.EnumerateObject()) { property.WriteTo(writer); } writer.WriteEndObject(); writer.Flush(); } SheetSettings docCopy = DeserializeFromFile(file); string jsonCopy = JsonSerializer.Serialize(docCopy, jsonOptions); Assert.NotNull(jsonCopy); Assert.Equal(jsonCopy, jsonString); }
public void TestPersist() { SheetSettings doc = new SheetSettings(); string json = JsonSerializer.Serialize(doc, jsonOptions); Assert.NotNull(json); Assert.True(json.Length > 0); SheetSettings doc2 = JsonSerializer.Deserialize <SheetSettings>(json); Assert.NotNull(doc2); }
/// <summary> /// Intiializes a new instance of the ImportAnimationView class /// </summary> /// <param name="controller">The controller owning this form</param> /// <param name="parentSheet">Optional AnimationSheet that will own the newly created animation</param> public ImportAnimationView(Controller controller, AnimationSheet parentSheet = null) { _controller = controller; _parentSheet = parentSheet; InitializeComponent(); cpb_sheetPreview.HookToControl(this); cpb_sheetPreview.Importer = controller.DefaultImporter; _spriteSheet = null; _sheetSettings = new SheetSettings(false, 32, 32); ValidateFields(); }
/** * Constructor, taking the sheet settings. This object just * takes the various fields from the bean in which it is interested * * @param the sheet settings */ public SetupRecord(SheetSettings s) : base(Type.SETUP) { orientation = s.getOrientation(); order = s.getPageOrder(); headerMargin = s.getHeaderMargin(); footerMargin = s.getFooterMargin(); paperSize = s.getPaperSize().getValue(); horizontalPrintResolution = s.getHorizontalPrintResolution(); verticalPrintResolution = s.getVerticalPrintResolution(); fitWidth = s.getFitWidth(); fitHeight = s.getFitHeight(); pageStart = s.getPageStart(); scaleFactor = s.getScaleFactor(); copies = s.getCopies(); initialized = true; }
public IExcelConfiguration HasSheetSetting(Action <SheetSetting> configAction, int sheetIndex = 0) { if (sheetIndex >= 0 && configAction != null) { if (SheetSettings.TryGetValue(sheetIndex, out var sheetSetting)) { configAction.Invoke(sheetSetting); } else { SheetSettings[sheetIndex] = sheetSetting = new SheetSetting(); } configAction.Invoke(sheetSetting); } return(this); }
/// <summary> /// Loads an image import preview /// </summary> /// <param name="previewImage">The image to use as preview</param> /// <param name="sheetSettings">The sheet settings</param> public void LoadPreview(Image previewImage, SheetSettings sheetSettings) { UnloadExportSheet(); // Reset the transformations scale = new PointF(1, 1); offsetPoint = Point.Empty; Image = previewImage; _sheetSettings = sheetSettings; _frameRects = Importer.GenerateFrameBounds(Image, sheetSettings); RefreshFrameBoundsPreview(); Invalidate(); UpdateScrollbars(); }
/// <summary> Constructor /// /// </summary> /// <param name="fr">the formatting records /// </param> /// <param name="sst">the shared string table /// </param> /// <param name="f">the excel file /// </param> /// <param name="sb">the bof record which indicates the start of the sheet /// </param> /// <param name="wb">the bof record which indicates the start of the sheet /// </param> /// <param name="wp">the workbook which this sheet belongs to /// </param> /// <param name="sp">the start position of the sheet bof in the excel file /// </param> /// <param name="sh">the sheet /// </param> /// <param name="nf">1904 date record flag /// </param> /// <exception cref=""> BiffException /// </exception> internal SheetReader(File f, SSTRecord sst, FormattingRecords fr, BOFRecord sb, BOFRecord wb, bool nf, WorkbookParser wp, int sp, SheetImpl sh) { excelFile = f; sharedStrings = sst; formattingRecords = fr; sheetBof = sb; workbookBof = wb; columnInfosArray = new ArrayList(); sharedFormulas = new ArrayList(); hyperlinks = new ArrayList(); rowProperties = new ArrayList(10); charts = new ArrayList(); drawings = new ArrayList(); nineteenFour = nf; workbook = wp; startPosition = sp; sheet = sh; settings = new SheetSettings(); workbookSettings = workbook.Settings; }
/// <summary> /// Refreshes the sheet settings object /// </summary> private void RefreshSheetSettings() { if (_spriteSheet == null) { return; } _sheetSettings = new SheetSettings { FrameWidth = (int)nud_width.Value, FrameHeight = (int)nud_height.Value, FrameCount = (int)nud_frameCount.Value, FirstFrame = (int)nud_skipCount.Value, FlipFrames = cb_reverseFrameOrder.Checked, OffsetX = (int)nud_startX.Value, OffsetY = (int)nud_startY.Value }; cpb_sheetPreview.SheetSettings = _sheetSettings; GenerateAnimationPreview(); }
/** * Reads in the contents of this sheet */ public void readSheet() { // If this sheet contains only a chart, then set everything to // empty and do not bother parsing the sheet // Thanks to steve.brophy for spotting this if (!sheetBof.isWorksheet()) { numRows = 0; numCols = 0; cells = new Cell[0, 0]; // return; } SheetReader reader = new SheetReader(excelFile, sharedStrings, formattingRecords, sheetBof, workbookBof, nineteenFour, workbook, startPosition, this); reader.read(); // Take stuff that was read in numRows = reader.getNumRows(); numCols = reader.getNumCols(); cells = reader.getCells(); rowProperties = reader.getRowProperties(); columnInfosArray = reader.getColumnInfosArray(); hyperlinks = reader.getHyperlinks(); conditionalFormats = reader.getConditionalFormats(); autoFilter = reader.getAutoFilter(); charts = reader.getCharts(); drawings = reader.getDrawings(); dataValidation = reader.getDataValidation(); mergedCells = reader.getMergedCells(); settings = reader.getSettings(); settings.setHidden(hidden); rowBreaks = reader.getRowBreaks(); columnBreaks = reader.getColumnBreaks(); workspaceOptions = reader.getWorkspaceOptions(); plsRecord = reader.getPLS(); buttonPropertySet = reader.getButtonPropertySet(); maxRowOutlineLevel = reader.getMaxRowOutlineLevel(); maxColumnOutlineLevel = reader.getMaxColumnOutlineLevel(); reader = null; //if (!workbookSettings.getGCDisabled()) // { // System.gc(); // } if (columnInfosArray.Count > 0) { ColumnInfoRecord cir = (ColumnInfoRecord) columnInfosArray[columnInfosArray.Count - 1]; columnInfos = new ColumnInfoRecord[cir.getEndColumn() + 1]; } else { columnInfos = new ColumnInfoRecord[0]; } // Add any local names if (localNames != null) { foreach (NameRecord nr in localNames) { if (nr.getBuiltInName() == BuiltInName.PRINT_AREA) { if (nr.getRanges().Length > 0) { NameRecord.NameRange rng = nr.getRanges()[0]; settings.setPrintArea(rng.getFirstColumn(), rng.getFirstRow(), rng.getLastColumn(), rng.getLastRow()); } } else if (nr.getBuiltInName() == BuiltInName.PRINT_TITLES) { // There can be 1 or 2 entries. // Row entries have hardwired column entries (first and last // possible column) // Column entries have hardwired row entries (first and last // possible row) for (int i = 0; i < nr.getRanges().Length; i++) { NameRecord.NameRange rng = nr.getRanges()[i]; if (rng.getFirstColumn() == 0 && rng.getLastColumn() == 255) { settings.setPrintTitlesRow(rng.getFirstRow(), rng.getLastRow()); } else { settings.setPrintTitlesCol(rng.getFirstColumn(), rng.getLastColumn()); } } } } } }
// This method will be called once at the end of pipeline execution; if no input is received, this method is not called protected override async Task EndProcessingAsync() { await base.EndProcessingAsync().ConfigureAwait(true); Log.Debug("EndProcessingAsync"); if (Config) { Process proc = null; try { var psi = new ProcessStartInfo { UseShellExecute = true, // This is important FileName = ServiceLocator.Current.SettingsService.SettingsFileName }; proc = Process.Start(psi); } catch (Win32Exception e) { // TODO: Better error message (output of stderr?) ServiceLocator.Current.TelemetryService.TrackException(e, false); Log.Error(e, $"Couldn't open settings file {ServiceLocator.Current.SettingsService.SettingsFileName}."); } finally { proc?.Dispose(); } return; } if (WinPrint.Core.Models.ModelLocator.Current.Settings == null) { Log.Fatal(new Exception($"Settings are invalid. See {ServiceLocator.Current.LogService.LogPath} for more information."), ""); return; } SetupUpdateHandler(); // Check for new version if (_installUpdate) { await DoUpdateAsync().ConfigureAwait(true); CleanUpUpdateHandler(); return; } if (_psObjects.Count == 0) { Log.Debug("No objects..."); if (string.IsNullOrEmpty(FileName)) { //Return if no objects or file specified CleanUpUpdateHandler(); return; } } // Whenever we run, check for an update. We use the cancellation token to kill the thread that's doing this // if we exit before getting a version info result back. Checking for updates should never shlow cmd line down. Log.Debug("Kicking off update check thread..."); await Task.Run(() => ServiceLocator.Current.UpdateService.GetLatestVersionAsync(_getVersionCancellationToken.Token).ConfigureAwait(true), _getVersionCancellationToken.Token).ConfigureAwait(true); var rec = new ProgressRecord(1, "Printing", "Printing...") { PercentComplete = 0, StatusDescription = "Initializing winprint" }; WriteProgress(rec); Debug.Assert(_print != null); if (!string.IsNullOrEmpty(PrinterName)) { try { rec.PercentComplete = 10; rec.StatusDescription = $"Setting printer name to {PrinterName}"; WriteProgress(rec); _print.SetPrinter(PrinterName); } catch (InvalidPrinterException) { Log.Information("Installed printers:"); foreach (string printer in PrinterSettings.InstalledPrinters) { Log.Information(" {printer}", printer); } Log.Fatal(new Exception($"{PrinterName} is not a valid printer name. Valid printer names include " + $"{string.Join(", ", PrinterSettings.InstalledPrinters.ToDynamicList().ToArray())}."), ""); CleanUpUpdateHandler(); return; } } if (string.IsNullOrEmpty(Title)) { if (string.IsNullOrEmpty(FileName)) { Title = MyInvocation.MyCommand.Name; } else { Title = FileName; } } // Core requires a fully qualified path. If FileName was provided, ensure it's fully qualified. // Note, Title stays as was provided via -FileName or -Title if (!string.IsNullOrEmpty(FileName) && !Path.IsPathFullyQualified(FileName)) { FileName = Path.GetFullPath(FileName, SessionState.Path.CurrentFileSystemLocation.Path); } SheetSettings sheet = null; string sheetID = null; try { MyInvocation.BoundParameters.TryGetValue("SheetDefinition", out var sheetDefinition); sheet = _print.SheetViewModel.FindSheet((string)sheetDefinition, out sheetID); rec.PercentComplete = 20; rec.StatusDescription = $"Setting Sheet Settings for {sheet.Name}"; WriteProgress(rec); if (Orientation.HasValue) { sheet.Landscape = Orientation == PortraitLandscape.Landscape; } if (LineNumbers.HasValue) { sheet.ContentSettings.LineNumbers = LineNumbers == YesNo.Yes; } // Must set landscape after printer/paper selection _print.PrintDocument.DefaultPageSettings.Landscape = sheet.Landscape; _print.SheetViewModel.SetSheet(sheet); } catch (InvalidOperationException e) { Log.Fatal(new Exception($"Could not find sheet settings. {e.Message}. See {ServiceLocator.Current.LogService.LogPath} for more information."), ""); CleanUpUpdateHandler(); return; } // If Language is provided, use it instead of CTE. if (!MyInvocation.BoundParameters.TryGetValue("Language", out var contentType)) { if (!MyInvocation.BoundParameters.TryGetValue("ContentTypeEngine", out contentType)) { // If neither were specified, smartly pick CTE contentType = ContentTypeEngineBase.GetContentType(FileName); } } if (MyInvocation.BoundParameters.TryGetValue("PaperSize", out var paperSize)) { _print.SetPaperSize((string)paperSize); } rec.PercentComplete = 30; rec.StatusDescription = $"Loading content"; WriteProgress(rec); _print.SheetViewModel.File = FileName; _print.SheetViewModel.Title = Title; _print.PrintingSheet += (s, sheetNum) => { if (sheetNum > 60) { rec.PercentComplete = 95; } else { rec.PercentComplete = 40 + sheetNum; } rec.StatusDescription = $"Printing sheet {sheetNum}"; WriteProgress(rec); Log.Information("Printing sheet {sheetNum}", sheetNum); }; try { if (_psObjects.Count == 0 && !string.IsNullOrEmpty(FileName)) { if (!Path.IsPathFullyQualified(FileName)) { FileName = Path.GetFullPath(FileName, SessionState.Path.CurrentFileSystemLocation.Path); } await _print.SheetViewModel.LoadFileAsync(FileName, (string)contentType).ConfigureAwait(true); } else { // Get $input into a string we can use // See: https://stackoverflow.com/questions/60712580/invoking-cmdlet-from-a-c-based-pscmdlet-providing-input-and-capturing-output var textToPrint = SessionState.InvokeCommand.InvokeScript(@"$input | Out-String", true, PipelineResultTypes.None, _psObjects, null)[0].ToString(); _print.SheetViewModel.Encoding = Encoding.UTF8; await _print.SheetViewModel.LoadStringAsync(textToPrint, (string)contentType).ConfigureAwait(true); } if (_verbose) { Log.Information("FileName: {FileName}", FileName ?? ""); Log.Information("Title: {title}", Title ?? ""); Log.Information("Content Type: {contentType}", _print.SheetViewModel.ContentType); Log.Information("Language: {Language}", _print.SheetViewModel.Language); Log.Information("Content Type Engine: {cte}", _print.SheetViewModel.ContentEngine.GetType().Name); Log.Information("Printer: {printer}", _print.PrintDocument.PrinterSettings.PrinterName); Log.Information("Paper Size: {size}", _print.PrintDocument.DefaultPageSettings.PaperSize.PaperName); Log.Information("Orientation: {s}", _print.PrintDocument.DefaultPageSettings.Landscape ? $"Landscape" : $"Portrait"); Log.Information("Sheet Definition: {name} ({id})", sheet.Name, sheetID); } } catch (System.IO.DirectoryNotFoundException dnfe) { Log.Error(dnfe, "Print failed."); CleanUpUpdateHandler(); return; } catch (System.IO.FileNotFoundException fnfe) { Log.Error(fnfe, "Print failed."); CleanUpUpdateHandler(); return; } catch (InvalidOperationException ioe) { // TODO: Use our own execptions Log.Error(ioe, "Print failed."); CleanUpUpdateHandler(); return; } rec.PercentComplete = 40; rec.StatusDescription = WhatIf ? "Counting" : $"Printing"; WriteProgress(rec); var sheetsCounted = 0; try { var sheetRangeSet = false; if (FromSheet != 0) { _print.PrintDocument.PrinterSettings.FromPage = FromSheet; sheetRangeSet = true; } else { _print.PrintDocument.PrinterSettings.FromPage = 0; } if (ToSheet != 0) { _print.PrintDocument.PrinterSettings.ToPage = ToSheet; sheetRangeSet = true; } else { _print.PrintDocument.PrinterSettings.ToPage = 0; } if (sheetRangeSet) { Log.Information("Printing from sheet {from} to sheet {to}.", _print.PrintDocument.PrinterSettings.FromPage, _print.PrintDocument.PrinterSettings.ToPage); } if (WhatIf) { sheetsCounted = await _print.CountSheets().ConfigureAwait(true); } else { sheetsCounted = await _print.DoPrint().ConfigureAwait(true); } } catch (System.ComponentModel.Win32Exception w32e) { // This can happen when PDF driver can't access PDF file. Log.Error(w32e, "Print failed."); CleanUpUpdateHandler(); return; } // Finalize Progress rec.PercentComplete = -1; rec.StatusDescription = $"Complete"; WriteProgress(rec); // Output via verbose how much printing got done if (_verbose) { Log.Information($"{(WhatIf ? "Would have printed" : "Printed")} {{sheetsCounted}} sheets.", sheetsCounted); } // End by sharing update info, if any if (!string.IsNullOrEmpty(_updateMsg)) { Log.Information(_updateMsg); } CleanUpUpdateHandler(); // Very last thing we do is write to the output if WhatIf was specified if (WhatIf) { WriteObject(sheetsCounted, false); } }
/** * Constructor, taking the sheet settings. This object just * takes the various fields from the bean in which it is interested * * @param the sheet settings */ public SetupRecord(SheetSettings s) : base(Type.SETUP) { orientation = s.getOrientation(); order = s.getPageOrder(); headerMargin = s.getHeaderMargin(); footerMargin = s.getFooterMargin(); paperSize = s.getPaperSize().getValue(); horizontalPrintResolution = s.getHorizontalPrintResolution(); verticalPrintResolution = s.getVerticalPrintResolution(); fitWidth = s.getFitWidth(); fitHeight = s.getFitHeight(); pageStart = s.getPageStart(); scaleFactor = s.getScaleFactor(); copies = s.getCopies(); initialized = true; }
/** * Sets the sheet settings for this particular sheet. Must be * called immediately prior to writing * * @param sr the sheet settings */ public void setSettings(SheetSettings sr) { settings = sr; }
/** * Sets the sheet settings for this particular sheet. Must be * called immediately prior to writing * * @param sr the sheet settings */ public void setSettings(SheetSettings sr) { settings = sr; }
/** * Constructor * * @param fr the formatting records * @param sst the shared string table * @param f the excel file * @param sb the bof record which indicates the start of the sheet * @param wb the bof record which indicates the start of the sheet * @param wp the workbook which this sheet belongs to * @param sp the start position of the sheet bof in the excel file * @param sh the sheet * @param nf 1904 date record flag * @exception BiffException */ public SheetReader(File f, SSTRecord sst, FormattingRecords fr, BOFRecord sb, BOFRecord wb, bool nf, WorkbookParser wp, int sp, SheetImpl sh) { excelFile = f; sharedStrings = sst; formattingRecords = fr; sheetBof = sb; workbookBof = wb; columnInfosArray = new ArrayList(); sharedFormulas = new ArrayList(); hyperlinks = new ArrayList(); conditionalFormats = new ArrayList(); rowProperties = new ArrayList(10); charts = new ArrayList(); drawings = new ArrayList(); outOfBoundsCells = new ArrayList(); nineteenFour = nf; workbook = wp; startPosition = sp; sheet = sh; settings = new SheetSettings(sh); workbookSettings = workbook.getSettings(); }