.NET (1273)
Children categories
Sometimes, hide row and column can make the data processing job easier and more efficient when working with a large excel file. However, hidden rows and columns are always hidden and invisible, for this reason, you need to unhide them before showing the whole excel file.
Spire.XLS for WPF provides developers four methods: HideRow(), HideColumn(), ShowRow() and ShowColumn() to hide or unhide excel row and column in WPF.
Please check the screenshot of the original excel worksheet:
Before using the code, make sure that Spire.XLS is installed on system correctly, next create a WPF application project and add the dll file from the installation folder as reference, after that use following namespace:
using System.Windows; using Spire.Xls;
Code snippets:
Step 1: Initialize a new instance of Workbook class and load the original excel file.
Workbook workbook = new Workbook(); workbook.LoadFromFile("Excel.xlsx");
Step 2: Get the first worksheet of the file.
Worksheet sheet = workbook.Worksheets[0];
Step 3: Hide or unhide row and column.
Hide the 8th row and the 3rd column:
sheet.HideRow(8); sheet.HideColumn(3);
Unhide:
sheet.ShowRow(8); sheet.ShowColumn(3);
Step 4: Save and launch the file.
Effective screenshot after hiding:
Full codes:
using Spire.Xls; using System.Windows; namespace WpfApplication1 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { //initialize a new instance Workbook workbook = new Workbook(); //load the sample excel file workbook.LoadFromFile("Excel.xlsx"); //get its first worksheet Worksheet sheet = workbook.Worksheets[0]; //hide the 8th row and the 3rd column of the first worksheet sheet.HideRow(8); sheet.HideColumn(3); /*//unhide sheet.ShowRow(8); sheet.ShowColumn(3);*/ //save and launch the file workbook.SaveToFile("Sample.xlsx", ExcelVersion.Version2010); System.Diagnostics.Process.Start(workbook.FileName); } } }
Create, Write and Save Excel File in WPF with C#, VB.NET
2016-01-29 08:39:34 Written by support iceblueCreating, Writing and Saving Excel file are basic tasks in our daily life. This guide will demonstrate how to create an Excel file, insert some data and save the file with specified file format using Spire.XLS for WPF.
Apart from creating Excel from scratch, Spire.XLS also supports to load an existing Excel file, modify the data and do a large range of manipulations in Excel.
Code Snippets:
Step 1: Initialize a new instance of Workbook class. By default, three blank worksheets will be added into the workbook accordingly.
Workbook workbook = new Workbook();
Step 2: Get the first worksheet from workbook and rename the sheet as "Test”.
Worksheet sheet = workbook.Worksheets[0]; sheet.Name = "Test";
Step 3: Insert some text value and number value into the specified cells.
sheet.Range["A1"].Text = "Text"; sheet.Range["A2"].Text = "Number"; sheet.Range["B1"].Text = "Hello World"; sheet.Range["B2"].NumberValue = 3.1415926; sheet.Range["A7"].Text = "This Excel file is created by Spire.XLS for WPF";
Step 4: Save the file in the format of Excel 2013.
workbook.SaveToFile("sample.xlsx",ExcelVersion.Version2013);
Output:
Full Code:
using Spire.Xls; using System.Windows; namespace WpfApplication1 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { Workbook workbook = new Workbook(); Worksheet sheet = workbook.Worksheets[0]; sheet.Name = "Test"; sheet.Range["A1"].Text = "Text"; sheet.Range["A2"].Text = "Number"; sheet.Range["B1"].Text = "Hello World"; sheet.Range["B2"].NumberValue = 3.1415926; sheet.Range["A7"].Text = "This Excel file is created by Spire.XLS for WPF"; workbook.SaveToFile("sample.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("sample.xlsx"); } } }
Imports Spire.Xls Imports System.Windows Namespace WpfApplication1 Public Partial Class MainWindow Inherits Window Public Sub New() InitializeComponent() End Sub Private Sub button1_Click(sender As Object, e As RoutedEventArgs) Dim workbook As New Workbook() Dim sheet As Worksheet = workbook.Worksheets(0) sheet.Name = "Test" sheet.Range("A1").Text = "Text" sheet.Range("A2").Text = "Number" sheet.Range("B1").Text = "Hello World" sheet.Range("B2").NumberValue = 3.1415926 sheet.Range("A7").Text = "This Excel file is created by Spire.XLS for WPF" workbook.SaveToFile("sample.xlsx", ExcelVersion.Version2013) System.Diagnostics.Process.Start("sample.xlsx") End Sub End Class End Namespace
How to Save Excel chart as Image for WPF applications
2016-01-27 08:43:53 Written by support iceblueWith the help of Spire.XLS for WPF, developers can easily save the whole Excel Worksheet to Image for their WPF applications. Sometimes we don’t want to share the whole Excel file with data to others and only want to show some charts on the Excel. Spire.XLS for WPF offers a method of workbook.SaveChartAsImage(); to enable us to save the Excel chart to image easily. In the following section, we will demonstrate how to save the Excel chart as image in .png for example for WPF applications.
Firstly, please view the whole Excel worksheet with data and two charts, a pie chart and a bar chart:
Note: Before Start, please download the latest version of Spire.XLS and add Spire.Xls.Wpf.dll in the bin folder as the reference of Visual Studio.
Here comes to the code snippets of how to save excel chart as image:
Step 1: Create a new Excel workbook and load from file.
Workbook workbook = new Workbook(); workbook.LoadFromFile("Sample.xlsx", ExcelVersion.Version2010);
Step 2: Get the first worksheet from workbook.
Worksheet sheet = workbook.Worksheets[0];
Step 3: Save all the charts in the first worksheet as images.
System.Drawing.Image[] imgs = workbook.SaveChartAsImage(sheet); for (int i = 0; i < imgs.Length; i++) { imgs[i].Save(string.Format("img-{0}.png", i), ImageFormat.Png); }
Effective screenshots:
Full codes:
using Spire.Xls; using System.Drawing.Imaging; using System.Windows; namespace WpfApplication1 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void button2_Click(object sender, RoutedEventArgs e) { Workbook workbook = new Workbook(); workbook.LoadFromFile("Sample.xlsx", ExcelVersion.Version2010); Worksheet sheet = workbook.Worksheets[0]; System.Drawing.Image[] imgs = workbook.SaveChartAsImage(sheet); for (int i = 0; i < imgs.Length; i++) { imgs[i].Save(string.Format("img-{0}.png", i), ImageFormat.Png); } } } }
Insert a Paragraph to Word Document in WPF with C#, VB.NET
2016-01-22 03:37:12 Written by support iceblueUsing Spire.Doc for WPF, programmers can easily create, open, modify and save Word documents in WPF applications. In this article, we’ll introduce how to insert a paragraph to desired position in an existing Word document.
To begin with, you need to download Spire.Doc for WPF and add the Spire.Doc.Wpf.dll and Spire.License.dll as the references to your WPF project. Then add a button in MainWindow and double click the button to write code.
Here are code snippets in the button click event:
Step 1: Initialize a new instance of Document class and load the sample Word document.
Document document = new Document(); document.LoadFromFile("sample.docx", FileFormat.Docx);
Step 2: Initialize a new instance of Paragraph class and append some text to it.
Paragraph paraInserted = new Paragraph(document); TextRange textRange1 = paraInserted.AppendText("Hello, this is a new paragraph.");
Step 3: Set the text formatting of the paragraph.
textRange1.CharacterFormat.TextColor = System.Drawing.Color.Purple; textRange1.CharacterFormat.FontSize = 11; textRange1.CharacterFormat.FontName = "Calibri Light";
Step 4: Insert the paragraph at the first section at index 1, which indicates the position of the second paragraph in the section.
document.Sections[0].Paragraphs.Insert(1, paraInserted);
Step 5: Save the file.
document.SaveToFile("result.docx", FileFormat.Docx);
Output:
Full Code:
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Windows; namespace WpfApplication1 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { Document document = new Document(); document.LoadFromFile("sample.docx", FileFormat.Docx); Paragraph paraInserted = new Paragraph(document); TextRange textRange1 = paraInserted.AppendText("Hello, this is a new paragraph."); textRange1.CharacterFormat.TextColor = System.Drawing.Color.Purple; textRange1.CharacterFormat.FontSize = 11; textRange1.CharacterFormat.FontName = "Calibri Light"; document.Sections[0].Paragraphs.Insert(1, paraInserted); document.SaveToFile("result.docx", FileFormat.Docx); } } }
Imports Spire.Doc Imports Spire.Doc.Documents Imports Spire.Doc.Fields Imports System.Windows Namespace WpfApplication1 Public Partial Class MainWindow Inherits Window Public Sub New() InitializeComponent() End Sub Private Sub button1_Click(sender As Object, e As RoutedEventArgs) Dim document As New Document() document.LoadFromFile("sample.docx", FileFormat.Docx) Dim paraInserted As New Paragraph(document) Dim textRange1 As TextRange = paraInserted.AppendText("Hello, this is a new paragraph.") textRange1.CharacterFormat.TextColor = System.Drawing.Color.Purple textRange1.CharacterFormat.FontSize = 11 textRange1.CharacterFormat.FontName = "Calibri Light" document.Sections(0).Paragraphs.Insert(1, paraInserted) document.SaveToFile("result.docx", FileFormat.Docx) End Sub End Class End Namespace
This article is going to introduce how to create, write and save word document in WPF via Spire.Doc for WPF.
Spire.Doc for WPF enables users to do a large range of manipulations (such as create, write, open, edit, convert and save, etc.) on word with high performance and efficiency. In addition, as a powerful and independent library, it doesn’t require Microsoft Office or any other 3rd party tools to be installed on system.
Note: please download and install Spire.Doc correctly and add the dll file from the installation folder as reference.
First, let’s begin to create a word document in WPF.
Use namespace:
using System.Windows; using Spire.Doc; using Spire.Doc.Documents;
Step 1: Create a new word document instance, next add a section and a paragraph to it.
//Create New Word Document doc = new Document(); //Add Section Section section = doc.AddSection(); //Add Paragraph Paragraph Para = section.AddParagraph();
Second, we’re going to write something into the document.
Step 2: Append some text to it.
//Append Text Para.AppendText("Hello! " + "I was created by Spire.Doc for WPF, it's a professional .NET Word component " + "which enables developers to perform a large range of tasks on Word document (such as create, open, write, edit, save and convert " + "Word document) without installing Microsoft Office and any other third-party tools on system.");
Third, save the generated document.
Step 3: Save and launch the document.
//Save and launch doc.SaveToFile("MyWord.docx", FileFormat.Docx); System.Diagnostics.Process.Start("MyWord.docx");
Output:
Full codes:
using Spire.Doc; using Spire.Doc.Documents; using System.Windows; namespace WpfApplication1 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { //Create New Word Document doc = new Document(); //Add Section Section section = doc.AddSection(); //Add Paragraph Paragraph Para = section.AddParagraph(); //Append Text Para.AppendText("Hello! " + "I was created by Spire.Doc for WPF, it's a professional .NET Word component " + "which enables developers to perform a large range of tasks on Word document (such as create, open, write, edit, save and convert " + "Word document) without installing Microsoft Office and any other third-party tools on system."); //Save and launch doc.SaveToFile("MyWord.docx", Spire.Doc.FileFormat.Docx); System.Diagnostics.Process.Start("MyWord.docx"); } } }
Embed uninstalled fonts by font document when convert word to PDF
2016-01-21 08:27:32 Written by support iceblueWe have already shown you how to use uninstalled font by font document when converting word to PDF. Now starts from Spire.Doc 5.6.3, Spire.Doc newly supports to set the font styles for the uninstalled fonts when convert word documents to PDF. Here comes to the code snippets of how to set the font styles for embed the uninstalled fonts by font documents:
Note: Before Start, please download the latest version of Spire.XLS and add Spire.xls.dll in the bin folder as the reference of Visual Studio.
Step 1: Create a new workbook and load from file.
Document document = new Document(); document.LoadFromFile("Testing.docx");
Step 2: Create an instance for class ToPdfParameterList named parms.
ToPdfParameterList parms = new ToPdfParameterList();
Step 3: Define the path of the uninstalled fonts.
{ new PrivateFontPath("Century Gothic",FontStyle.Regular,"fonts\\GOTHIC.TTF"), new PrivateFontPath("Century Gothic",FontStyle.Bold,"fonts\\GOTHICB.TTF"), new PrivateFontPath("Century Gothic",FontStyle.Italic,"fonts\\GOTHICI.TTF") , new PrivateFontPath("Century Gothic",FontStyle.Bold|FontStyle.Italic,"fonts\\GOTHICBI.TTF") };
Step 4: Save the document to file and launch to preview it.
document.SaveToFile("Testing.pdf", parms); System.Diagnostics.Process.Start("Testing.pdf");
Effective screenshot of the embedded uninstalled fonts by setting the font style after converts to PDF:
class Program { static void Main(string[] args) { string DEMOPATH = @"..\..\Documents\Myppt14.pptx"; // Retrieve the number of slides, excluding the hidden slides. Console.WriteLine(RetrieveNumberOfSlides(DEMOPATH, false)); // Retrieve the number of slides, including the hidden slides. Console.WriteLine(RetrieveNumberOfSlides(DEMOPATH)); Console.ReadKey(); } public static int RetrieveNumberOfSlides(string fileName, bool includeHidden = true) { int slidesCount = 0; using (PresentationDocument doc = PresentationDocument.Open(fileName, false)) { // Get the presentation part of the document. PresentationPart presentationPart = doc.PresentationPart; if (presentationPart != null) { if (includeHidden) { slidesCount = presentationPart.SlideParts.Count(); } else { // Each slide can include a Show property, which if hidden // will contain the value "0". The Show property may not // exist, and most likely will not, for non-hidden slides. var slides = presentationPart.SlideParts.Where( (s) => (s.Slide != null) && ((s.Slide.Show == null) || (s.Slide.Show.HasValue && s.Slide.Show.Value))); slidesCount = slides.Count(); } } } return slidesCount; } }
class Program { static void Main(string[] args) { MoveSlide(@"..\..\Documents\Myppt13.pptx", 0, 1); } // Counting the slides in the presentation. public static int CountSlides(string presentationFile) { // Open the presentation as read-only. using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, false)) { // Pass the presentation to the next CountSlides method // and return the slide count. return CountSlides(presentationDocument); } } // Count the slides in the presentation. public static int CountSlides(PresentationDocument presentationDocument) { // Check for a null document object. if (presentationDocument == null) { throw new ArgumentNullException("presentationDocument"); } int slidesCount = 0; // Get the presentation part of document. PresentationPart presentationPart = presentationDocument.PresentationPart; // Get the slide count from the SlideParts. if (presentationPart != null) { slidesCount = presentationPart.SlideParts.Count(); } // Return the slide count to the previous method. return slidesCount; } // Move a slide to a different position in the slide order in the presentation. public static void MoveSlide(string presentationFile, int from, int to) { using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, true)) { MoveSlide(presentationDocument, from, to); } } // Move a slide to a different position in the slide order in the presentation. public static void MoveSlide(PresentationDocument presentationDocument, int from, int to) { if (presentationDocument == null) { throw new ArgumentNullException("presentationDocument"); } // Call the CountSlides method to get the number of slides in the presentation. int slidesCount = CountSlides(presentationDocument); // Verify that both from and to positions are within range and different from one another. if (from < 0 || from >= slidesCount) { throw new ArgumentOutOfRangeException("from"); } if (to < 0 || from >= slidesCount || to == from) { throw new ArgumentOutOfRangeException("to"); } // Get the presentation part from the presentation document. PresentationPart presentationPart = presentationDocument.PresentationPart; // The slide count is not zero, so the presentation must contain slides. Presentation presentation = presentationPart.Presentation; SlideIdList slideIdList = presentation.SlideIdList; // Get the slide ID of the source slide. SlideId sourceSlide = slideIdList.ChildElements[from] as SlideId; SlideId targetSlide = null; // Identify the position of the target slide after which to move the source slide. if (to == 0) { targetSlide = null; } if (from < to) { targetSlide = slideIdList.ChildElements[to] as SlideId; } else { targetSlide = slideIdList.ChildElements[to - 1] as SlideId; } // Remove the source slide from its current position. sourceSlide.Remove(); // Insert the source slide at its new position after the target slide. slideIdList.InsertAfter(sourceSlide, targetSlide); // Save the modified presentation. presentation.Save(); } }
class Program { static void Main(string[] args) { string sourceFile = @"..\..\Documents\Myppt12.pptx"; string targetFile = @"..\..\Documents\Myppt11.pptx"; MoveParagraphToPresentation(sourceFile, targetFile); } // Moves a paragraph range in a TextBody shape in the source document // to another TextBody shape in the target document. public static void MoveParagraphToPresentation(string sourceFile, string targetFile) { // Open the source file as read/write. using (PresentationDocument sourceDoc = PresentationDocument.Open(sourceFile, true)) { // Open the target file as read/write. using (PresentationDocument targetDoc = PresentationDocument.Open(targetFile, true)) { // Get the first slide in the source presentation. SlidePart slide1 = GetFirstSlide(sourceDoc); // Get the first TextBody shape in it. TextBody textBody1 = slide1.Slide.Descendants().First(); // Get the first paragraph in the TextBody shape. // Note: "Drawing" is the alias of namespace DocumentFormat.OpenXml.Drawing Drawing.Paragraph p1 = textBody1.Elements().First(); // Get the first slide in the target presentation. SlidePart slide2 = GetFirstSlide(targetDoc); // Get the first TextBody shape in it. TextBody textBody2 = slide2.Slide.Descendants().First(); // Clone the source paragraph and insert the cloned. paragraph into the target TextBody shape. // Passing "true" creates a deep clone, which creates a copy of the // Paragraph object and everything directly or indirectly referenced by that object. textBody2.Append(p1.CloneNode(true)); // Remove the source paragraph from the source file. textBody1.RemoveChild(p1); // Replace the removed paragraph with a placeholder. textBody1.AppendChild(new Drawing.Paragraph()); // Save the slide in the source file. slide1.Slide.Save(); // Save the slide in the target file. slide2.Slide.Save(); } } } // Get the slide part of the first slide in the presentation document. public static SlidePart GetFirstSlide(PresentationDocument presentationDocument) { // Get relationship ID of the first slide PresentationPart part = presentationDocument.PresentationPart; SlideId slideId = part.Presentation.SlideIdList.GetFirstChild(); string relId = slideId.RelationshipId; // Get the slide part by the relationship ID. SlidePart slidePart = (SlidePart)part.GetPartById(relId); return slidePart; } }
class Program { static void Main(string[] args) { InsertNewSlide(@"..\..\Documents\Myppt2.pptx", 1, "My new slide"); } // Insert a slide into the specified presentation. public static void InsertNewSlide(string presentationFile, int position, string slideTitle) { // Open the source document as read/write. using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, true)) { // Pass the source document and the position and title of the slide to be inserted to the next method. InsertNewSlide(presentationDocument, position, slideTitle); } } // Insert the specified slide into the presentation at the specified position. public static void InsertNewSlide(PresentationDocument presentationDocument, int position, string slideTitle) { if (presentationDocument == null) { throw new ArgumentNullException("presentationDocument"); } if (slideTitle == null) { throw new ArgumentNullException("slideTitle"); } PresentationPart presentationPart = presentationDocument.PresentationPart; // Verify that the presentation is not empty. if (presentationPart == null) { throw new InvalidOperationException("The presentation document is empty."); } // Declare and instantiate a new slide. Slide slide = new Slide(new CommonSlideData(new ShapeTree())); uint drawingObjectId = 1; // Construct the slide content. // Specify the non-visual properties of the new slide. NonVisualGroupShapeProperties nonVisualProperties = slide.CommonSlideData.ShapeTree.AppendChild(new NonVisualGroupShapeProperties()); nonVisualProperties.NonVisualDrawingProperties = new NonVisualDrawingProperties() { Id = 1, Name = "" }; nonVisualProperties.NonVisualGroupShapeDrawingProperties = new NonVisualGroupShapeDrawingProperties(); nonVisualProperties.ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties(); // Specify the group shape properties of the new slide. slide.CommonSlideData.ShapeTree.AppendChild(new GroupShapeProperties()); // Declare and instantiate the title shape of the new slide. Shape titleShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape()); drawingObjectId++; // Specify the required shape properties for the title shape. titleShape.NonVisualShapeProperties = new NonVisualShapeProperties (new NonVisualDrawingProperties() { Id = drawingObjectId, Name = "Title" }, new NonVisualShapeDrawingProperties(new Drawing.ShapeLocks() { NoGrouping = true }), new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title })); titleShape.ShapeProperties = new ShapeProperties(); // Specify the text of the title shape. titleShape.TextBody = new TextBody(new Drawing.BodyProperties(), new Drawing.ListStyle(), new Drawing.Paragraph(new Drawing.Run(new Drawing.Text() { Text = slideTitle }))); // Declare and instantiate the body shape of the new slide. Shape bodyShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape()); drawingObjectId++; // Specify the required shape properties for the body shape. bodyShape.NonVisualShapeProperties = new NonVisualShapeProperties(new NonVisualDrawingProperties() { Id = drawingObjectId, Name = "Content Placeholder" }, new NonVisualShapeDrawingProperties(new Drawing.ShapeLocks() { NoGrouping = true }), new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Index = 1 })); bodyShape.ShapeProperties = new ShapeProperties(); // Specify the text of the body shape. bodyShape.TextBody = new TextBody(new Drawing.BodyProperties(), new Drawing.ListStyle(), new Drawing.Paragraph()); // Create the slide part for the new slide. SlidePart slidePart = presentationPart.AddNewPart(); // Save the new slide part. slide.Save(slidePart); // Modify the slide ID list in the presentation part. // The slide ID list should not be null. SlideIdList slideIdList = presentationPart.Presentation.SlideIdList; // Find the highest slide ID in the current list. uint maxSlideId = 1; SlideId prevSlideId = null; foreach (SlideId slideId in slideIdList.ChildElements) { if (slideId.Id > maxSlideId) { maxSlideId = slideId.Id; } position--; if (position == 0) { prevSlideId = slideId; } } maxSlideId++; // Get the ID of the previous slide. SlidePart lastSlidePart; if (prevSlideId != null) { lastSlidePart = (SlidePart)presentationPart.GetPartById(prevSlideId.RelationshipId); } else { lastSlidePart = (SlidePart)presentationPart.GetPartById(((SlideId)(slideIdList.ChildElements[0])).RelationshipId); } // Use the same slide layout as that of the previous slide. if (null != lastSlidePart.SlideLayoutPart) { slidePart.AddPart(lastSlidePart.SlideLayoutPart); } // Insert the new slide into the slide list after the previous slide. SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId); newSlideId.Id = maxSlideId; newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart); // Save the modified presentation. presentationPart.Presentation.Save(); } }