protected override void ProcessRecord() { if (parFile.StartsWith(@".\")) { parFile = System.IO.Path.Combine(this.CurrentProviderLocation("FileSystem").ProviderPath, parFile.Substring(2)); } parFile = System.IO.Path.GetFullPath(parFile); try { string destName = string.Format("{0}\\{1}.{2}", Path.GetDirectoryName(parFile), Path.GetFileNameWithoutExtension(parFile), formatName); WriteVerbose(string.Format("Will convert {0} to {1}", parFile, destName)); if (System.IO.File.Exists(destName) && !parOverwrite) { WriteError(new ErrorRecord(new UnauthorizedAccessException(string.Format("File already exists and overwrite not specified", destName)), "200", ErrorCategory.PermissionDenied, destName)); } else { IDynamic doc = msWord.Property("Documents").Get().Method("Open").AddParameter(parFile).AddMissingParameters(15).Invoke(); doc.Method("SaveAs").AddRefParameter(destName).AddRefParameter(format).Invoke(); if (!parNoExit) { doc.Method("Close").AddParameter(0).Invoke(); } } } catch (Exception ex) { WriteError(new ErrorRecord(new InvalidDataException(string.Format("Conversion failed: {0}", ex.Message)), "201", ErrorCategory.ParserError, parFile)); } }
protected override void EndProcessing() { base.StopProcessing(); WriteVerbose("Done processing files"); msExcel.Method("Quit").Invoke(); WriteVerbose("Reverting culture"); Thread.CurrentThread.CurrentCulture = currentCulture; }
protected override void EndProcessing() { base.StopProcessing(); WriteVerbose("Done processing files"); if (parNoExit) { WriteVerbose("-NoExit specified, making word visible if not already"); msWord.Property("Visible").Set(true); } else { WriteVerbose("-NoExit not specified, quitting word"); msWord.Method("Quit").AddParameter(0).Invoke(); } }
protected override void EndProcessing() { base.StopProcessing(); WriteVerbose("Done processing files"); if (parNoExit) { WriteVerbose("-NoExit specified, making excel visible if not already"); msExcel.Property("Visible").Set(true); } else { WriteVerbose("-NoExit not specified, quitting excel"); msExcel.Method("Quit").Invoke(); } WriteVerbose("Reverting culture"); Thread.CurrentThread.CurrentCulture = currentCulture; }
protected override void BeginProcessing() { base.BeginProcessing(); if (!(GetOfficeVersion.GetVersion("Excel")).IsInstalled) { ThrowTerminatingError(new ErrorRecord(new FileNotFoundException("Excel is not installed use Out-OExcel instead."), "1", ErrorCategory.InvalidOperation, null)); } if (parPath.StartsWith(@".\")) { parPath = System.IO.Path.Combine(this.CurrentProviderLocation("FileSystem").ProviderPath, parPath.Substring(2)); } parPath = System.IO.Path.GetFullPath(parPath); WriteVerbose(string.Format("Checking for existance of file {0}", parPath)); WriteProgress(new ProgressRecord(10, "Out-Excel", "Initializing..")); if (File.Exists(parPath)) { if (!parOverwrite) { WriteVerbose("File exists and -Overwrite have not been specified"); ThrowTerminatingError(new ErrorRecord(new System.IO.IOException("The file already exists and -Overwrite have not been specified"), "100", ErrorCategory.ResourceExists, parPath.ToString())); } else { WriteVerbose("File exists and -Override have been specified, will delete file"); File.Delete(Path); } } WriteVerbose("Starting Microsoft Excel"); msExcel = BindingFactory.CreateAutomationBinding("Excel.Application"); currentCulture = Thread.CurrentThread.CurrentCulture; int langSettings = msExcel.Property("LanguageSettings").Get().Property("LanguageID").PropertyParam(2).Get <int>(); CultureInfo newCulture = new CultureInfo(langSettings); WriteVerbose(string.Format("Changing culture ({0}->{1})", currentCulture.DisplayName, newCulture.DisplayName)); Thread.CurrentThread.CurrentCulture = newCulture; if (parDisplay) { WriteVerbose("Display have been set, making application visible"); msExcel.Property("Visible").Set(true); } WriteProgress(new ProgressRecord(10, "Out-Excel", "Creating document..")); try { WriteVerbose("Creating new document"); workBook = msExcel.Property("Workbooks").Get().Method("Add").Invoke(); } catch { workBook.Method("Close").AddParameter(0).Invoke(); msExcel.Method("Quit").AddParameter(0).Invoke(); WriteVerbose("Document creation failed "); ThrowTerminatingError(new ErrorRecord(new System.IO.IOException("Document creation failed"), "101", ErrorCategory.ResourceUnavailable, msExcel)); } WriteVerbose("Activating document"); workBook.Method("Activate").Invoke(); }
protected override void EndProcessing() { base.EndProcessing(); if (tableStyle == string.Empty) { tableStyle = "TableStyleMedium9"; } WriteVerbose("Setting table styles"); WriteProgress(new ProgressRecord(10, "Out-Excel", "Formatting tables..")); IDynamic dynamicWorksheets = workBook.Property("Worksheets").Get(); int tableCount = dynamicWorksheets.Property("Count").Get <int>(); for (int i = 1; (i - 1) < tableCount; i++) { //worksheet.ListObjects.Add(XlListObjectSourceType.xlSrcRange,worksheet.Range("A1",worksheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell)), Type.Missing, XlYesNoGuess.xlYes,"Table1",tableStyle); IDynamic worksheet = dynamicWorksheets.Index(i).Get(); IDynamic endCell = worksheet.Property("Cells").Get().Property("SpecialCells").PropertyParam(11).Get(); IDynamic range = worksheet.Property("Range").PropertyParam("A1").PropertyParam(GetExcelCellName(endCell.Property("Column").Get <int>(), endCell.Property("Row").Get <int>())).Get(); worksheet.Property("Columns").Get().Method("AutoFit").Invoke(); worksheet.Property("ListObjects").Get().Method("Add").AddParameter(1).AddParameter(range.InstanceObject).AddMissingParameters(1).AddParameter(1).AddParameter("Table1").AddParameter(tableStyle).Invoke(); } WriteProgress(new ProgressRecord(10, "Out-Excel", "Saving document..")); int format = 0; switch (parFormat.ToLower()) { case "excel": format = 51; break; case "excel97": format = 56; break; case "pdf": format = 57; break; case "xps": format = 58; break; } WriteVerbose(string.Format("Saving document in {0}", parFormat)); try { workBook.Method("SaveAs").AddRefParameter(parPath).AddRefParameter(format).Invoke(); } catch (Exception ex) { WriteVerbose("Save failed, see error log for details"); if (parNoExit) { WriteVerbose("-NoExit specified, making word visible if not already"); msExcel.Property("Visible").Set(true); } else { WriteVerbose("-NoExit not specified, quitting Excel"); workBook.Method("Close").AddParameter(0).Invoke(); msExcel.Method("Quit").Invoke(); } ThrowTerminatingError(new ErrorRecord(ex, "300", ErrorCategory.FromStdErr, parPath)); } if (parNoExit) { WriteVerbose("-NoExit specified, making Excel visible if not already"); msExcel.Property("Visible").Set(true); } else { WriteVerbose("-NoExit not specified, quitting word"); workBook.Method("Close").AddParameter(0).Invoke(); msExcel.Method("Quit").Invoke(); } WriteVerbose("Reverting culture"); Thread.CurrentThread.CurrentCulture = currentCulture; WriteProgress(new ProgressRecord(10, "Out-Excel", "Done")); WriteVerbose("Done"); WriteObject(new FileInfo(parPath)); }
protected override void BeginProcessing() { base.BeginProcessing(); if (!(GetOfficeVersion.GetVersion("Excel")).IsInstalled) { ThrowTerminatingError(new ErrorRecord(new FileNotFoundException("Excel is not installed use Import-OExcelWorkbook instead."), "1", ErrorCategory.InvalidOperation, null)); } msExcel = BindingFactory.CreateAutomationBinding("Excel.Application"); currentCulture = Thread.CurrentThread.CurrentCulture; int langSettings = msExcel.Property("LanguageSettings").Get().Property("LanguageID").PropertyParam(2).Get <int>(); CultureInfo newCulture = new CultureInfo(langSettings); WriteVerbose(string.Format("Changing culture ({0}->{1})", currentCulture.DisplayName, newCulture.DisplayName)); Thread.CurrentThread.CurrentCulture = newCulture; if (parFile.StartsWith(@".\")) { parFile = System.IO.Path.Combine(this.CurrentProviderLocation("FileSystem").ProviderPath, parFile.Substring(2)); } parFile = System.IO.Path.GetFullPath(parFile); if (!System.IO.File.Exists(parFile)) { msExcel.Method("Quit").Invoke(); ThrowTerminatingError(new ErrorRecord(new FileNotFoundException(string.Format("The source file does not exist", parFile)), "200", ErrorCategory.OpenError, parFile)); } IDynamic nativeWorkbook = null; try { nativeWorkbook = msExcel.Property("Workbooks").Get().Method("Open").AddParameter(parFile).AddMissingParameters(14).Invoke(); FileInfo fileInfo = new FileInfo(parFile); Workbook workbook = new Workbook(); workbook.Filepath = parFile; workbook.FileIsReadOnly = fileInfo.IsReadOnly; workbook.FileLastModified = fileInfo.LastWriteTime; workbook.FileCreated = fileInfo.CreationTime; workbook.Author = nativeWorkbook.Property("Author").Get <string>(); workbook.Title = nativeWorkbook.Property("Title").Get <string>(); workbook.Comments = nativeWorkbook.Property("Comments").Get <string>(); workbook.Keywords = nativeWorkbook.Property("Keywords").Get <string>(); workbook.Worksheets = GetWorksheets(nativeWorkbook); WriteObject(workbook); } catch (Exception ex) { WriteError(new ErrorRecord(new InvalidDataException(string.Format("Conversion failed: {0}", ex.Message)), "201", ErrorCategory.ParserError, parFile)); } finally { if (nativeWorkbook != null) { nativeWorkbook.Method("Close").AddParameter(0).Invoke(); } msExcel.Method("Quit").Invoke(); } }
protected override void ProcessRecord() { base.ProcessRecord(); if (parObject == null) { WriteVerbose("A null object found in the pipe, ignoring it."); } else { if (parObject.GetType() != lastObject) { WriteVerbose("New object type detected"); WriteProgress(new ProgressRecord(10, "Out-Word", "Creating new table..")); lastObject = parObject.GetType(); int columns = 0; foreach (PSMemberInfo property in parObject.Properties) { columns++; } if (columns > 63) { wordDoc.Method("Close").AddParameter(0).Invoke(); msWord.Method("Quit").AddParameter(0).Invoke(); WriteVerbose("To many properties detected on the object"); ThrowTerminatingError(new ErrorRecord(new IndexOutOfRangeException("One or more objects exceeds 63 properties which is maximum in Word"), "200", ErrorCategory.InvalidData, parObject)); } else { WriteVerbose(string.Format("Adding header (#{0})", headerCount++)); WriteProgress(new ProgressRecord(10, "Out-Word", string.Format("Adding header (#{0})", headerCount))); currentTable = wordDoc.Property("Tables").Get().Method("Add").AddParameter(currentRange.InstanceObject).AddParameter(1).AddParameter(columns).Invoke(); currentRange = currentTable.Property("Range").Get(); int headerCounter = 1; foreach (PSMemberInfo property in parObject.Properties) { IDynamic cell = currentTable.Method("Cell").AddParameter(1).AddParameter(headerCounter).Invoke().Property("Range").Get(); try { cell.Property("Style").Set(wordTableHeaderStyle); } catch { WriteWarning(string.Format("The style specified for table header rows ('{0}') was not found", wordTableHeaderStyle)); } cell.Method("InsertAfter").AddParameter(property.Name).Invoke(); headerCounter++; } } } WriteVerbose(string.Format("Adding object row (#{0})", rowCount++)); WriteProgress(new ProgressRecord(10, "Out-Word", string.Format("Adding row (#{0})", rowCount))); currentTable.Property("Rows").Get().Method("Add").Invoke(); int colCounter = 1; foreach (PSMemberInfo property in parObject.Properties) { IDynamic cell = currentTable.Method("Cell").AddParameter(rowCount + 1).AddParameter(colCounter).Invoke().Property("Range").Get(); try { cell.Property("Style").Set(wordTableRowStyle); } catch { WriteWarning(string.Format("The style specified for table rows ('{0}') was not found", wordTableRowStyle)); } try { cell.Method("InsertAfter").AddParameter(property.Value.ToString()).Invoke(); } catch { //this.WriteError(new ErrorRecord(new NullReferenceException(string.Format("Property ({0}) contains null value",property.Name)),"900",ErrorCategory.InvalidData,parObject)); } colCounter++; } } }
protected override void BeginProcessing() { base.BeginProcessing(); if (!(GetOfficeVersion.GetVersion("Word")).IsInstalled) { ThrowTerminatingError(new ErrorRecord(new FileNotFoundException("Excel is not installed use Out-OWord instead."), "1", ErrorCategory.InvalidOperation, null)); } if (parPath.StartsWith(@".\")) { parPath = System.IO.Path.Combine(this.CurrentProviderLocation("FileSystem").ProviderPath, parPath.Substring(2)); } parPath = System.IO.Path.GetFullPath(parPath); WriteVerbose(string.Format("Checking for existance of file {0}", parPath)); WriteProgress(new ProgressRecord(10, "Out-Word", "Initializing..")); if (File.Exists(parPath)) { if (!parOverwrite) { WriteVerbose("File exists and -Overwrite have not been specified"); ThrowTerminatingError(new ErrorRecord(new System.IO.IOException("The file already exists and -Overwrite have not been specified"), "100", ErrorCategory.ResourceExists, parPath.ToString())); } else { WriteVerbose("File exists and -Override have been specified, will delete file"); File.Delete(Path); } } WriteVerbose("Starting Microsoft Word"); msWord = BindingFactory.CreateAutomationBinding("Word.Application"); if (parDisplay) { WriteVerbose("Display have been set, making application visible"); msWord.Property("Visible").Set(true); } WriteProgress(new ProgressRecord(10, "Out-Word", "Creating document..")); try { WriteVerbose("Creating new document"); wordDoc = msWord.Property("Documents").Get().Method("Add").AddParameter(Template).AddParameter(false).AddParameter(0).AddParameter(true).Invoke(); } catch { msWord.Method("Quit").AddParameter(0).Invoke(); WriteVerbose("Document creation failed (error in template most likely)"); ThrowTerminatingError(new ErrorRecord(new System.IO.IOException("Template not valid/found"), "101", ErrorCategory.ResourceUnavailable, parTemplate)); } //WriteVerbose("Activating document"); //msWord.Method("Activate").Invoke(); if (wordTitleStyle == string.Empty) { wordTitleStyle = wordDoc.Property("Styles").Get().Index(-63).Get().Property("NameLocal").Get <string>(); //wordTitleStyle = wordDoc.Styles[WdBuiltinStyle.wdStyleTitle].NameLocal; WriteVerbose(string.Format("Default localized TITLE style is: {0}", wordTitleStyle)); } if (wordHeaderStyle == string.Empty) { //wordHeaderStyle = wordDoc.Styles[WdBuiltinStyle.wdStyleNormal].NameLocal; wordHeaderStyle = wordDoc.Property("Styles").Get().Index(-1).Get().Property("NameLocal").Get <string>(); WriteVerbose(string.Format("Default localized HEADER style is: {0}", wordHeaderStyle)); } if (wordFooterStyle == string.Empty) { //wordFooterStyle = wordDoc.Styles[WdBuiltinStyle.wdStyleQuote].NameLocal; wordFooterStyle = wordDoc.Property("Styles").Get().Index(-181).Get().Property("NameLocal").Get <string>(); WriteVerbose(string.Format("Default localized FOOTER style is: {0}", wordFooterStyle)); } if (wordTableStyle == string.Empty) { //wordTableStyle = wordDoc.Styles[WdBuiltinStyle.wdStyleTableMediumList1Accent1].NameLocal; wordTableStyle = wordDoc.Property("Styles").Get().Index(-178).Get().Property("NameLocal").Get <string>(); WriteVerbose(string.Format("Default localized TABLE style is: {0}", wordTableStyle)); } if (wordTableHeaderStyle == string.Empty) { //wordTableHeaderStyle = wordDoc.Styles[WdBuiltinStyle.wdStyleIntenseEmphasis].NameLocal; wordTableHeaderStyle = wordDoc.Property("Styles").Get().Index(-262).Get().Property("NameLocal").Get <string>(); WriteVerbose(string.Format("Default localized TABLEHEADER style is: {0}", wordTableHeaderStyle)); } if (wordTableRowStyle == string.Empty) { //wordTableRowStyle = wordDoc.Styles[WdBuiltinStyle.wdStyleEmphasis].NameLocal; wordTableRowStyle = wordDoc.Property("Styles").Get().Index(-89).Get().Property("NameLocal").Get <string>(); WriteVerbose(string.Format("Default localized TABLEROW style is: {0}", wordTableRowStyle)); } currentRange = msWord.Property("Selection").Get().Property("Range").Get(); WriteProgress(new ProgressRecord(10, "Out-Word", "Creating title and headers..")); if (parTitle != String.Empty) { WriteVerbose("Adding title"); IDynamic newPara = wordDoc.Property("Paragraphs").Get().Method("Add").Invoke(); try { newPara.Property("Style").Set(wordTitleStyle); } catch { WriteWarning(string.Format("The style specified for document title ('{0}') was not found", wordTitleStyle)); } newPara.Property("Range").Get().Property("Text").Set(parTitle); newPara.Property("Range").Get().Method("InsertParagraphAfter").Invoke(); currentRange = newPara.Property("Range").Get(); } if (parHeader != String.Empty) { WriteVerbose("Adding header"); IDynamic newPara = wordDoc.Property("Paragraphs").Get().Method("Add").Invoke(); try { newPara.Property("Style").Set(wordHeaderStyle); } catch { WriteWarning(string.Format("The style specified for document header ('{0}') was not found", wordHeaderStyle)); } newPara.Property("Range").Get().Property("Text").Set(parHeader); newPara.Property("Range").Get().Method("InsertParagraphAfter").Invoke(); currentRange = newPara.Property("Range").Get(); } }