C#/VB.NET: Convert CSV to PDF

2022-07-07 08:46:00 Written by Koohji

CSV is one of the commonly used file formats for exchanging tabular data between applications. However, in some circumstances, CSV may not be the most appropriate file format. For instance, if you have a CSV report that needs to be sent to an important customer, the best way to ensure the file appears as-is on the customer's device is to convert it to PDF. This article will demonstrate how to convert CSV to PDF in C# and VB.NET using Spire.XLS for .NET.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.XLS

Convert CSV to PDF in C# and VB.NET

The following are the steps to convert a CSV file to PDF:

  • Create an instance of Workbook class.
  • Load the CSV file using Workbook.LoadFromFile(filePath, separator) method.
  • Set the Workbook.ConverterSetting.SheetFitToPage property as true to ensure the worksheet is rendered to one PDF page.
  • Get the first worksheet in the Workbook using Workbook.Worksheets[0] property.
  • Loop through the columns in the worksheet and auto-fit the width of each column using Worksheet.AutoFitColumn() method.
  • Save the worksheet to PDF using Worksheet.SaveToPdf() method.
  • C#
  • VB.NET
using Spire.Xls;

namespace ConvertCsvToPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook wb = new Workbook();
            //Load a CSV file
            wb.LoadFromFile("Sample.csv", ",");

            //Set SheetFitToPage property as true to ensure the worksheet is converted to 1 PDF page
            wb.ConverterSetting.SheetFitToPage = true;

            //Get the first worksheet
            Worksheet sheet = wb.Worksheets[0];

            //Loop through the columns in the worksheet
            for (int i = 1; i < sheet.Columns.Length; i++)
            {
                //AutoFit columns
                sheet.AutoFitColumn(i);
            }

            //Save the worksheet to PDF
            sheet.SaveToPdf("toPDF.pdf");
        }
    }
}

C#/VB.NET: Convert CSV to PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Shapes are powerful tools for improving the aesthetics and functionality of your Excel documents. Whether you're looking to add visual elements to charts, highlight important data, or create engaging presentations, mastering shape manipulation is essential. In this article, we will explore how to add, format, and remove shapes in Excel in C# using Spire.XLS for .NET, providing you with practical tips and techniques to elevate your spreadsheet.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.XLS

Add Shapes in Excel in C#

Spire.XLS for .NET provides the Worksheet.PrstGeomShapes.AddPrstGeomShape(int row, int column, int width, int height, PrstGeomShapeType shapeType) method for adding shapes to a worksheet. The first four parameters define the shape's position and dimensions, while the fifth parameter specifies the shape type. The PrstGeomShapeType enumeration includes 188 different shape types preset in Excel.

To add a specific type of shape to a worksheet in C#, follow these steps:

  • Create a Workbook object.
  • Get a specific worksheet using the Workbook.Worksheets[index] property.
  • Add a shape to the worksheet using the Worksheet.PrstGeomShapes.AddPrstGeomShape() method, specifying the location, size and type of the shape.
  • Save the workbook to an Excel file.

The following code demonstrates how to generate an Excel file and add various geometric shapes, including a rectangle, a triangle, a heart, a pie, and a smiley face, using the Spire.XLS for .NET library.

  • C#
using Spire.Xls;
using Spire.Xls.Core;

namespace AddShapesInExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();

            // Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            // Add a rectangle
            IPrstGeomShape rectangle = sheet.PrstGeomShapes.AddPrstGeomShape(3, 2, 270, 40, PrstGeomShapeType.Rect);

            // Set text for the shape
            rectangle.Text = "Add various types of shapes to Excel";
            rectangle.TextVerticalAlignment = ExcelVerticalAlignment.MiddleCentered;

            // Add a triangle, a pie, a curved right arrow, a heart, a smile face, and an octagon to the worksheet
            sheet.PrstGeomShapes.AddPrstGeomShape(8, 2, 100, 100, PrstGeomShapeType.Triangle);
            sheet.PrstGeomShapes.AddPrstGeomShape(8, 6, 100, 100, PrstGeomShapeType.Pie);
            sheet.PrstGeomShapes.AddPrstGeomShape(8, 10, 100, 100, PrstGeomShapeType.CurvedRightArrow);

            sheet.PrstGeomShapes.AddPrstGeomShape(18, 2, 100, 100, PrstGeomShapeType.Heart);
            sheet.PrstGeomShapes.AddPrstGeomShape(18, 6, 100, 100, PrstGeomShapeType.SmileyFace);
            sheet.PrstGeomShapes.AddPrstGeomShape(18, 10, 100, 100, PrstGeomShapeType.Octagon);

            // Save the workbook to an Excel file
            workbook.SaveToFile("AddShapes.xlsx", ExcelVersion.Version2016);

            // Dispose resources
            workbook.Dispose();
        }
    }
}

Various types of shapes added in a worksheet

Format Shapes in Excel in C#

Formatting shapes enhances the visual appeal of your worksheets and improves information conveyance. Spire.XLS for Java provides interfaces such as IShapeLineFormat, IShapeFill, and IShadow, enabling users to customize the line style, line color, fill, and shadow effect of a shape.

The steps to format a shape in Excel are as follows:

  • Create a Workbook object.
  • Get a specific worksheet using the Workbook.Worksheets[index] property.
  • Add a shape to the worksheet using the Worksheet.PrstGeomShapes.AddPrstGeomShape() method, specifying the location, size and type of the shape.
  • Get the IShapeLineFormat object through the IShape.Line property.
  • Set the line style, color, width and visibility using the properties under the IShapeLineFormat object.
  • Get the IShapeFill object through the IShape.Fill property.
  • Set the fill type, and fill color (or image, pattern, texture) using the properties under the IShapeFill object.
  • Save the workbook to an Excel file.

The following code demonstrates various methods for customizing shapes in Excel, including line styles, fill types (solid, gradient, pattern, texture), and the use of images.

  • C#
using Spire.Xls;
using Spire.Xls.Core;
using System.Drawing;

namespace FormatShapesInExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();

            // Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            // Add the first rectangle to the worksheet
            IPrstGeomShape rectangle_one = sheet.PrstGeomShapes.AddPrstGeomShape(4, 2, 220, 120, PrstGeomShapeType.Rect);

            // Set the line style, width, and color
            rectangle_one.Line.DashStyle = ShapeDashLineStyleType.Dashed;
            rectangle_one.Line.Weight = 1.0;
            rectangle_one.Line.ForeColor = Color.Red;

            // Set the fill type and fore color
            rectangle_one.Fill.FillType = ShapeFillType.SolidColor;
            rectangle_one.Fill.ForeColor = Color.LightGray;

            // Add the second rectangle and format the shape
            IPrstGeomShape rectangle_two = sheet.PrstGeomShapes.AddPrstGeomShape(4, 6, 220, 120, PrstGeomShapeType.Rect);
            rectangle_two.Line.Visible = false;
            rectangle_two.Fill.FillType = ShapeFillType.Gradient;
            rectangle_two.Fill.ForeColor = Color.LightGray;
            rectangle_two.Fill.GradientStyle = GradientStyleType.Vertical;

            // Add the third rectangle and format the shape
            IPrstGeomShape rectangle_three = sheet.PrstGeomShapes.AddPrstGeomShape(4, 10, 220, 120, PrstGeomShapeType.Rect);
            rectangle_three.Line.Weight = 1.0;
            rectangle_three.Fill.FillType = ShapeFillType.Pattern;
            rectangle_three.Fill.Pattern = GradientPatternType.Pat80Percent;
            rectangle_three.Fill.ForeColor = Color.White;
            rectangle_three.Fill.BackColor = Color.Pink;

            // Add the fourth rectangle and format the shape
            IPrstGeomShape rectangle_four = sheet.PrstGeomShapes.AddPrstGeomShape(15, 2, 220, 120, PrstGeomShapeType.Rect);
            rectangle_four.Line.Weight = 1.0;
            rectangle_four.Fill.CustomPicture("C:\\Users\\Administrator\\Desktop\\cartoon.jpeg");

            // Add the fifth rectangle and format the shape
            IPrstGeomShape rectangle_five = sheet.PrstGeomShapes.AddPrstGeomShape(15, 6, 220, 120, PrstGeomShapeType.Rect);
            rectangle_five.Line.Weight = 1.0;
            rectangle_five.Fill.FillType  = ShapeFillType.NoFill;

            // Add the sixth rectangle and format the shape
            IPrstGeomShape rectangle_six = sheet.PrstGeomShapes.AddPrstGeomShape(15, 10, 220, 120, PrstGeomShapeType.Rect);
            rectangle_six.Line.Weight = 1.0;
            rectangle_six.Fill.FillType = ShapeFillType.Texture;
            rectangle_six.Fill.Texture = GradientTextureType.Canvas;

            // Save the workbook to an Excel file
            workbook.SaveToFile("FormatShapes.xlsx", ExcelVersion.Version2016);

            // Dispose resources
            workbook.Dispose();
        }
    }
}

Several shapes in a worksheet formatted with different line styles and shape fills

Remove Shapes from Excel in C#

The Worksheet.PrstGeomShapes property returns a collection of shapes within a worksheet. To remove a specific shape from the collection, use the PrstGeomShapeCollection[index].Remove() method, where the index specifies the shape's position. To delete all shapes, you can iterate through the collection and remove each shape individually.

The steps to remove a shape in an Excel worksheet are as follows:

  • Create a Workbook object.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet through the Workbook.Worksheets[index] property.
  • Get the shape collection through the Worksheet.PrstGeomShapes property.
  • Remove a specific shape using the PrstGeomShapeCollection[index].Remove() method.
  • Save the workbook to a different Excel file.

The following code demonstrates how to load an existing Excel file, remove specific shapes or all shapes from a worksheet.

  • C#
using Spire.Xls;
using Spire.Xls.Core.Spreadsheet.Collections;

namespace RemoveShapesFromExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();

            // Load an Excel file
            workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Shapes.xlsx");

            // Get a specific worksheet
            Worksheet sheet = workbook.Worksheets[0];

            // Get the shape collection from the worksheet
            PrstGeomShapeCollection shapes = sheet.PrstGeomShapes;

            // Remove a specific shape
            shapes[1].Remove();

            /*
            // Remove all shapes
            for (int i = shapes.Count - 1; i >= 0; i--)
            {
                shapes[i].Remove();
            }
            */
            
            // Save the workbook to an Excel file
            workbook.SaveToFile("RemoveShape.xlsx", ExcelVersion.Version2013);

            // Dispose resources
            workbook.Dispose();
        }
    }
}

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Spire.Presentation has a powerful function to print PowerPoint document. From Spire.Presentation v 2.8.59, it supports to use the PrintDocument object to print the presentation slides. This example shows how to print presentation slides using C# via the following print methods:

  • Print PowerPoint document to default printer.
  • Print PowerPoint document to virtual printer.
  • Print some pages from the PowerPoint document and set the document name, number of copies while printing the presentation slides.

Print presentation slides to default printer and print all the pages on the PowerPoint document.

using Spire.Presentation;
using System.Drawing.Printing;
namespace PrintPPT
{

    class Program
    {

        static void Main(string[] args)
        {
            Presentation ppt = new Presentation();
            ppt.LoadFromFile("Sample.pptx");

            PresentationPrintDocument document = new PresentationPrintDocument(ppt);
            document.PrintController = new StandardPrintController();

            ppt.Print(document);


        }
    }
}

Print PowerPoint document to virtual printer (Microsoft XPS Document Writer).

using Spire.Presentation;
namespace PrintPPT
{

    class Program
    {

        static void Main(string[] args)
        {
            Presentation ppt = new Presentation();
            ppt.LoadFromFile("Sample.pptx");

            PresentationPrintDocument document = new PresentationPrintDocument(ppt);
            document.PrinterSettings.PrinterName = "Microsoft XPS Document Writer";

            ppt.Print(document);


        }
    }
}

Print some pages from the PowerPoint document and set the document name, number of copies while printing the presentation slides.

using Spire.Presentation;
using System.Drawing.Printing;
namespace PrintPPT
{

    class Program
    {

        static void Main(string[] args)
        {
            Presentation ppt = new Presentation();
            ppt.LoadFromFile("Sample.pptx");

            PresentationPrintDocument document = new PresentationPrintDocument(ppt);

            //Set the document name to display while printing the document  
            document.DocumentName = "Print PowerPoint";

            //Choose to print some pages from the PowerPoint document
            document.PrinterSettings.PrintRange = PrintRange.SomePages;
            document.PrinterSettings.FromPage = 1;
            document.PrinterSettings.ToPage = 2;

            //Set the number of copies of the document to print
            document.PrinterSettings.Copies = 2;

            ppt.Print(document);


        }
    }
}

Comments in Excel are blocks of text that can be added to cells, mainly used to provide additional explanation or supplemental information about the cell contents. Users can add comments to the specific cells to better explain the data of worksheets. However, sometimes too many comments will cause visual clutter or obstruct other content. To avoid this issue, existing comments can be hidden programmatically to make the worksheet more organized and readable. Hidden comments can also be easily displayed when necessary. In this article, you will learn how to hide or show comments in excel by using Spire.XLS for .NET.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS for.NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.XLS

Hide Comments in Excel

Spire.XLS for .NET provides the Worksheet.Comments[].IsVisble property to control the visibility of comments. You can easily hide existing comments by setting this property to "false". The following are the detailed steps to hide comments in excel.

  • Initialize a Workbook instance.
  • Load a sample file using Workbook.LoadFromFile() method.
  • Get the desired worksheet through Workbook.Worksheets[] property.
  • Hide the specific comment in the worksheet by setting Worksheet.Comments[].IsVisble property to "false".
  • Finally, save the result file using Workbook.SavaToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

namespace ShowExcelComments
{
    class Program
    {
        static void Main(string[] args)
        {
            {
                //Initialize a Workbook instance and load the excel document
                Workbook workbook = new Workbook();
                workbook.LoadFromFile("Comments.xlsx");

                //Get the first worksheet
                Worksheet sheet = workbook.Worksheets[0];

                //Hide the specific comment in the worksheet
                sheet.Comments[0].IsVisible = false;

                //Save the document
                workbook.SaveToFile("HideComment.xlsx", ExcelVersion.Version2013);
                workbook.Dispose();
            }
        }
    }
}

C#/VB.NET: Hide or Show Comments in Excel

Show Comments in Excel

Hidden comments can also be easily displayed when necessary. If you want to show it again, please set Worksheet.Comments[].IsVisble property to "ture". The following are the steps to show comments in excel.

  • Initialize a Workbook instance.
  • Load a sample file using Workbook.LoadFromFile() method.
  • Get the desired worksheet through Workbook.Worksheets[] property.
  • Show the specific comment in the worksheet By setting Worksheet.Comments[].IsVisble property to "true".
  • Finally, save the result file using Workbook.SavaToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

namespace ShowExcelComments
{
    class Program
    {
        static void Main(string[] args)
        {
            {
                //Initialize a Workbook instance and load the excel document
                Workbook workbook = new Workbook();
                workbook.LoadFromFile("HideComment.xlsx");

                //Get the first worksheet
                Worksheet sheet = workbook.Worksheets[0];

                //Show the specific comment in the worksheet
                sheet.Comments[0].IsVisible = true;

                //Save the document
                workbook.SaveToFile("ShowComment.xlsx", ExcelVersion.Version2013);
                workbook.Dispose();
            }
        }
    }
}

C#/VB.NET: Hide or Show Comments in Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

You may sometimes want your text to display vertically (letters stacked one on top of the other), horizontally, or rotated facing the right margin or the left margin. This tutorial shows you how to change the text direction using VerticalTextType property in Spire.Presentation.

Step 1: Initialize an instance of Prensentation class.

Presentation ppt = new Presentation();

Step 2: Append a shape with text to the first slide.

IAutoShape textboxShape = ppt.Slides[0].Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(50, 70, 100, 400));
textboxShape.ShapeStyle.LineColor.Color = Color.Transparent;
textboxShape.Fill.FillType = Spire.Presentation.Drawing.FillFormatType.Solid;
textboxShape.Fill.SolidColor.Color = Color.OrangeRed;
textboxShape.TextFrame.Text = "You Are Welcome Here";

Step 3: Set the text direction to vertical.

textboxShape.TextFrame.VerticalTextType = VerticalTextType.Vertical;

Step 4: Append another shape with text to the slide.

textboxShape = ppt.Slides[0].Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(150, 70, 100, 400));
textboxShape.ShapeStyle.LineColor.Color = Color.Transparent;
textboxShape.Fill.FillType = Spire.Presentation.Drawing.FillFormatType.Solid;
textboxShape.Fill.SolidColor.Color = Color.Orange;
textboxShape.TextFrame.Text = "欢迎光临";

Step 5: For asian characters, you can set the VerticalTextType as EastAsianVertical to aviod rotating text 90 degrees.

textboxShape.TextFrame.VerticalTextType = VerticalTextType.EastAsianVertical;

Step 6: Save the file.

ppt.SaveToFile("output.pptx", FileFormat.Pptx2013);

Output:

How to Change Text Direction in PowerPoint in C#, VB.NET

Full Code:

[C#]
using Spire.Presentation;
using System.Drawing;
namespace ChangeTextDirection
{
    class Program
    {
        static void Main(string[] args)
        {

            Presentation ppt = new Presentation();

            IAutoShape textboxShape = ppt.Slides[0].Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(50, 70, 100, 400));
            textboxShape.ShapeStyle.LineColor.Color = Color.Transparent;
            textboxShape.Fill.FillType = Spire.Presentation.Drawing.FillFormatType.Solid;
            textboxShape.Fill.SolidColor.Color = Color.OrangeRed;
            textboxShape.TextFrame.Text = "You Are Welcome Here";
            textboxShape.TextFrame.VerticalTextType = VerticalTextType.Vertical;

            textboxShape = ppt.Slides[0].Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(150, 70, 100, 400));
            textboxShape.ShapeStyle.LineColor.Color = Color.Transparent;
            textboxShape.Fill.FillType = Spire.Presentation.Drawing.FillFormatType.Solid;
            textboxShape.Fill.SolidColor.Color = Color.Orange;
            textboxShape.TextFrame.Text = "欢迎光临";
            textboxShape.TextFrame.VerticalTextType = VerticalTextType.EastAsianVertical;

            ppt.SaveToFile("output.pptx", FileFormat.Pptx2013);

        }
    }
}
[VB.NET]
Imports Spire.Presentation
Imports System.Drawing
Namespace ChangeTextDirection
	Class Program
		Private Shared Sub Main(args As String())

			Dim ppt As New Presentation()

			Dim textboxShape As IAutoShape = ppt.Slides(0).Shapes.AppendShape(ShapeType.Rectangle, New RectangleF(50, 70, 100, 400))
			textboxShape.ShapeStyle.LineColor.Color = Color.Transparent
			textboxShape.Fill.FillType = Spire.Presentation.Drawing.FillFormatType.Solid
			textboxShape.Fill.SolidColor.Color = Color.OrangeRed
			textboxShape.TextFrame.Text = "You Are Welcome Here"
			textboxShape.TextFrame.VerticalTextType = VerticalTextType.Vertical

			textboxShape = ppt.Slides(0).Shapes.AppendShape(ShapeType.Rectangle, New RectangleF(150, 70, 100, 400))
			textboxShape.ShapeStyle.LineColor.Color = Color.Transparent
			textboxShape.Fill.FillType = Spire.Presentation.Drawing.FillFormatType.Solid
			textboxShape.Fill.SolidColor.Color = Color.Orange
			textboxShape.TextFrame.Text = "欢迎光临"
			textboxShape.TextFrame.VerticalTextType = VerticalTextType.EastAsianVertical

			ppt.SaveToFile("output.pptx", FileFormat.Pptx2013)

		End Sub
	End Class
End Namespace

We have already demonstrated how to use Spire.PDF to add multiple layers to PDF file and delete layer in PDF in C#. We can also toggle the visibility of a PDF layer while creating a new page layer with the help of Spire.PDF. In this section, we're going to demonstrate how to toggle the visibility of layers in new PDF document in C#.

Step 1: Create a new PDF document and add a new page to the PDF document.

PdfDocument pdf = new PdfDocument();
PdfPageBase page = pdf.Pages.Add();

Step 2: Add a layer named "Blue line" to the PDF page and set the layer invisible.

PdfLayer layer = pdf.Layers.AddLayer(""Green line"", PdfVisibility.Off);
PdfPen pen = new PdfPen(Color.Green, 1f);
PdfCanvas pcA = layer.CreateGraphics(page.Canvas);
pcA.DrawLine(pen, new PointF(0, 30), new PointF(300, 30));

Step 3: Add a layer named "Ellipse" to the PDF page and set the layer visible.

layer = pdf.Layers.AddLayer(""Ellipse"", PdfVisibility.On);
 PdfPen pen2 = new PdfPen(Color.Green, 1f);
 PdfBrush brush2 = new PdfSolidBrush(Color.Green);
 PdfCanvas pcB = layer.CreateGraphics(page.Canvas);
 pcB.DrawEllipse(pen2, brush2, 50, 70, 200, 60);

Step 4: Save the document to file.

pdf.SaveToFile("LayerVisibility.pdf", FileFormat.PDF);

Effective screenshot after toggle the visibility of PDF layer:

How to toggle the visibility of PDF layer in C#

Full codes:

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;


namespace LayerVisibility
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument pdf = new PdfDocument();
            PdfPageBase page = pdf.Pages.Add();

            PdfLayer layer = pdf.Layers.AddLayer("Green line", PdfVisibility.Off);
            PdfPen pen = new PdfPen(Color.Green, 1f);
            PdfCanvas pcA = layer.CreateGraphics(page.Canvas);
            pcA.DrawLine(pen,new PointF(0, 30), new PointF(300, 30));

            layer = pdf.Layers.AddLayer("Ellipse", PdfVisibility.On);
            PdfPen pen2 = new PdfPen(Color.Green, 1f);
            PdfBrush brush2 = new PdfSolidBrush(Color.Green);
            PdfCanvas pcB = layer.CreateGraphics(page.Canvas);
            pcB.DrawEllipse(pen2, brush2, 50, 70, 200, 60);


            pdf.SaveToFile("LayerVisibility.pdf", FileFormat.PDF);
        }
    }
}

Add Tab Stops to Word Paragraphs in C#

2017-09-18 09:28:27 Written by Koohji

Tab stops are markers placed on the ruler that define how text or numbers are aligned on a line. To add tab stops to a paragraph in Microsoft Word, we need to open the Tabs dialog box and then set the tab stop position, alignment and leader as shown below.

Add Tab Stops to Word Paragraphs in C#

This article elaborates how to add tab stops to paragraphs in word document programmatically using Spire.Doc.

Detail steps:

Step 1: Instantiate a Document object and add a section to it.

Document document = new Document();
Section section = document.AddSection(); 

Step 2: Add paragraph 1 to the section.

Paragraph paragraph1 = section.AddParagraph();

Step 3: Add tab stops to paragraph 1.

//Add tab and set its position (in points)
Tab tab = paragraph1.Format.Tabs.AddTab(28);
//Set tab alignment
tab.Justification = TabJustification.Left;
//move to next tab and append text
paragraph1.AppendText("\tWashing Machine");

//Add another tab and set its position (in points)
tab = paragraph1.Format.Tabs.AddTab(280);
//Set tab alignment
tab.Justification = TabJustification.Left;
//Specify tab leader type
tab.TabLeader = TabLeader.Dotted;
//move to next tab and append text
paragraph1.AppendText("\t$650"); 

Step 4: Add paragraph 2 to the section.

Paragraph paragraph2 = section.AddParagraph();

Step 5: Add tab stops to paragraph 2.

//Add tab and set its position (in points)
tab = paragraph2.Format.Tabs.AddTab(28);
//Set tab alignment
tab.Justification = TabJustification.Left;
//move to next tab and append text
paragraph2.AppendText("\tRefrigerator");

//Add another tab and set its position (in points)
tab = paragraph2.Format.Tabs.AddTab(280);
//Set tab alignment
tab.Justification = TabJustification.Left;
//Specify tab leader type
tab.TabLeader = TabLeader.NoLeader;
//move to next tab and append text
paragraph2.AppendText("\t$800"); 

Step 6: Save and close the document object.

document.SaveToFile("Tab.docx", FileFormat.Docx2013);
document.Close();

Screenshot:

Add Tab Stops to Word Paragraphs in C#

Full code:

using Spire.Doc;
using Spire.Doc.Documents;
namespace AddTapStops
{
 class Program
    {

     static void Main(string[] args)
     {
         //Instantiate a Document object
         Document document = new Document();
         //Add a section
         Section section = document.AddSection();

         //Add paragraph 1
         Paragraph paragraph1 = section.AddParagraph();

         //Add tab and set its position (in points)
         Tab tab = paragraph1.Format.Tabs.AddTab(28);
         //Set tab alignment
         tab.Justification = TabJustification.Left;
         //move to next tab and append text
         paragraph1.AppendText("\tWashing Machine");

         //Add another tab and set its position (in points)
         tab = paragraph1.Format.Tabs.AddTab(280);
         //Set tab alignment
         tab.Justification = TabJustification.Left;
         //Specify tab leader type
         tab.TabLeader = TabLeader.Dotted;
         //move to next tab and append text
         paragraph1.AppendText("\t$650");

         //Add paragraph 2
         Paragraph paragraph2 = section.AddParagraph();

         //Add tab and set its position (in points)
         tab = paragraph2.Format.Tabs.AddTab(28);
         //Set tab alignment
         tab.Justification = TabJustification.Left;
         //move to next tab and append text
         paragraph2.AppendText("\tRefrigerator"); //move to next tab and append text

         //Add another tab and set its position (in points)
         tab = paragraph2.Format.Tabs.AddTab(280);
         //Set tab alignment
         tab.Justification = TabJustification.Left;
         //Specify tab leader type
         tab.TabLeader = TabLeader.NoLeader;
         //move to next tab and append text
         paragraph2.AppendText("\t$800");

         //Save and close the document object            
         document.SaveToFile("Tab.docx", FileFormat.Docx2013);
         document.Close();

     }

    }
}

With Spire.XLS for .NET, we could easily add different kinds of charts to Excel worksheet, such as Pie Chart, Column Chart, bar chart, line chart, radar chart, Doughnut chart, pyramid chart, etc. In this article, we'll show you how to remove chart from Excel worksheet by using Spire.XLS.

Below is a sample document which contains a chart and table from the Excel worksheet, then we'll remove the chart from the slide.

How to remove chart from Excel worksheet in C#, VB.NET

C# Code Snippet of how to remove the chart from Excel:

Step 1: Create an instance of Excel workbook and load the document from file.

Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");

Step 2: Get the first worksheet from the workbook.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Get the first chart from the first worksheet.

IChartShape chart = sheet.Charts[0];

Step 4: Remove the chart.

chart.Remove();

Step 5: Save the document to file.

workbook.SaveToFile("RemoveChart.xlsx");

Effective screenshot:

How to remove chart from Excel worksheet in C#, VB.NET

Full code:

[C#]
using Spire.Xls;
using Spire.Xls.Core;
namespace RemoveChart
{

    class Program
    {

        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");
            Worksheet sheet = workbook.Worksheets[0];
            IChartShape chart = sheet.Charts[0];
            chart.Remove();
            workbook.SaveToFile("RemoveChart.xlsx");

        }

    }
}
[VB.NET]
Imports Spire.Xls
Imports Spire.Xls.Core
Namespace RemoveChart

	Class Program

		Private Shared Sub Main(args As String())
			Dim workbook As New Workbook()
			workbook.LoadFromFile("Sample.xlsx")
			Dim sheet As Worksheet = workbook.Worksheets(0)
			Dim chart As IChartShape = sheet.Charts(0)
			chart.Remove()
			workbook.SaveToFile("RemoveChart.xlsx")

		End Sub

	End Class
End Namespace

In Word, textbox can contain multiple elements such as text, image and table. This article demonstrates how to insert table into word textbox, and read and delete existing table from word textbox using Spire.Doc.

Insert table

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace InsertTable
{
    class Program
    {

        static void Main(string[] args)
        {

            //Create a Document instance
            Document document = new Document();

            //Add a section
            Section section = document.AddSection();
            //Add a paragraph to the section
            Paragraph paragraph = section.AddParagraph();

            //Add textbox to the paragraph
            TextBox textbox = paragraph.AppendTextBox(300, 100);

            //Add text to textbox
            Paragraph textboxParagraph = textbox.Body.AddParagraph();
            TextRange textboxRange = textboxParagraph.AppendText("Table 1");
            textboxRange.CharacterFormat.FontName = "Arial";

            //Insert table to textbox
            Table table = textbox.Body.AddTable(true);
            //Specify the number of rows and columns of the table
            table.ResetCells(4, 4);

            string[,] data = new string[,]  
{  
{"Name","Age","Gender","ID" },  
{"John","28","Male","0023" },  
{"Steve","30","Male","0024" },  
{"Lucy","26","female","0025" }  
};

            //Add data to table 
            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    TextRange tableRange = table[i, j].AddParagraph().AppendText(data[i, j]);
                    tableRange.CharacterFormat.FontName = "Arial";
                }
            }

            //Apply style to table
            table.ApplyStyle(DefaultTableStyle.LightGridAccent3);

            //Save the document
            document.SaveToFile("Output.docx", FileFormat.Docx2013);

        }
    }
}

Insert, Read and Delete Table from Word Textbox in C#

Read table

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.IO;
using System.Text;
namespace ReadTable
{
    class Program
    {

        static void Main(string[] args)
        {
            //Create a Document instance and load the word document
            Document document = new Document("Output.docx");

            //Get the first textbox
            TextBox textbox = document.TextBoxes[0];

            //Get the first table in the textbox
            Table table = textbox.Body.Tables[0] as Table;

            StringBuilder sb = new StringBuilder();

            //Loop through the paragraphs of the table and extract text to a .txt file
            foreach (TableRow row in table.Rows)
            {
                foreach (TableCell cell in row.Cells)
                {
                    foreach (Paragraph paragraph in cell.Paragraphs)
                    {
                        sb.AppendLine(paragraph.Text);
                    }
                }
            }
            File.WriteAllText("text.txt", sb.ToString());

        }
    }
}

Insert, Read and Delete Table from Word Textbox in C#

Delete table

using Spire.Doc;
using Spire.Doc.Fields;
namespace DeleteTable
{
    class Program
    {

        static void Main(string[] args)
        {
            //Create a Document instance and load the word document
            Document document = new Document("Output.docx");

            //Get the first textbox
            TextBox textbox = document.TextBoxes[0];

            //Remove the first table from the textbox
            textbox.Body.Tables.RemoveAt(0);

            //Save the document
            document.SaveToFile("RemoveTable.docx", FileFormat.Docx2013);


        }
    }
}

Insert, Read and Delete Table from Word Textbox in C#

When creating charts from scratch in PowerPoint slide, an Excel sheet with some dummy data will automatically be generated. The dummy data can be overwritten with the data from data source as well as from an existing Excel file. This article demonstrates how we can create chart in PowerPoint using the data in Excel file.

This solution requires Spire.Presneation.dll and Spire.Xls.dll to be added as references in project. Please download Spire.Office and reference the corresponding DLLs from it.

Here is the Excel sheet containing our sample data.

How to Create Chart Using Excel Data in PowerPoint in C#, VB.NET

Step 1: Create a Presentation document.

Presentation ppt = new Presentation();

Step 2: Append a column chart in the first slide.

RectangleF rect = new RectangleF(40, 100, 550, 320);
IChart chart = ppt.Slides[0].Shapes.AppendChart(ChartType.ColumnClustered, rect);

Step 3: Clear the default dummy data.

chart.ChartData.Clear(0, 0, 5, 5);

Step 4: Load an existing Excel file to Workbook instance and get the first worksheet.

Workbook wb = new Workbook();
wb.LoadFromFile("data.xlsx");
Worksheet sheet = wb.Worksheets[0];

Step 5: Import data from the worksheet to chart table.

for (int r = 0; r < sheet.AllocatedRange.RowCount; r++)
{
    for (int c = 0; c < sheet.AllocatedRange.ColumnCount; c++)
    {
        chart.ChartData[r, c].Value = sheet.Range[r + 1, c + 1].Value2;
    }
}

Step 6: Set the series label and categories labels.

chart.Series.SeriesLabel = chart.ChartData["B1", "B1"];
chart.Categories.CategoryLabels = chart.ChartData["A2","A13"];

Step 7: Set the series values.

chart.Series[0].Values = chart.ChartData["B2","B13"];

Step 8: Save the file.

ppt.SaveToFile("chart.pptx",Spire.Presentation.FileFormat.Pptx2013);

Output:

How to Create Chart Using Excel Data in PowerPoint in C#, VB.NET

Full Code:

[C#]
using System;
using Spire.Presentation;
using System.Drawing;
using Spire.Presentation.Charts;
using Spire.Xls;

namespace CreateChartFromExcelData
{
    class Program
    {
        static void Main(string[] args)
        {
            //initialize an instance of Presentation class
            Presentation ppt = new Presentation();
            RectangleF rect = new RectangleF(40, 100, 550, 320);
            IChart chart = ppt.Slides[0].Shapes.AppendChart(ChartType.ColumnClustered, rect);

            //clear the default dummy data
            chart.ChartData.Clear(0, 0, 5, 5);

            //load an existing Excel file to Workbook object
            Workbook wb = new Workbook();
            wb.LoadFromFile("data.xlsx");
            Worksheet sheet = wb.Worksheets[0];

            //import data from the sheet to chart table
            for (int r = 0; r < sheet.AllocatedRange.RowCount; r++)
            {
                for (int c = 0; c < sheet.AllocatedRange.ColumnCount; c++)
                {
                    chart.ChartData[r, c].Value = sheet.Range[r + 1, c + 1].Value2;
                }
            }

            //add chart title
            chart.ChartTitle.TextProperties.Text = "Monthly Sales Report";
            chart.ChartTitle.TextProperties.IsCentered = true;
            chart.ChartTitle.Height = 30;
            chart.HasTitle = true;

            //set the series label
            chart.Series.SeriesLabel = chart.ChartData["B1", "B1"];

            //set the category labels
            chart.Categories.CategoryLabels = chart.ChartData["A2","A13"];

            //set the series values
            chart.Series[0].Values = chart.ChartData["B2","B13"];

            //save the file
            ppt.SaveToFile("chart.pptx",Spire.Presentation.FileFormat.Pptx2013);
        }
    }
}
[VB.NET]
Imports Spire.Presentation
Imports System.Drawing
Imports Spire.Presentation.Charts
Imports Spire.Xls

Namespace CreateChartFromExcelData
    Class Program
        Private Shared Sub Main(args As String())
			'initialize an instance of Presentation class
			Dim ppt As New Presentation()

            Dim rect As New RectangleF(40, 100, 550, 320)

            Dim chart As IChart = ppt.Slides(0).Shapes.AppendChart(ChartType.ColumnClustered, rect)

			'clear the default dummy data
			chart.ChartData.Clear(0, 0, 5, 5)

			'load an existing Excel file to Workbook object
			Dim wb As New Workbook()

            wb.LoadFromFile("data.xlsx")
			Dim sheet As Worksheet = wb.Worksheets(0)

			'import data from the sheet to chart table
			For r As Integer = 0 To sheet.AllocatedRange.RowCount - 1
				For c As Integer = 0 To sheet.AllocatedRange.ColumnCount - 1

                    chart.ChartData(r, c).Value = sheet.Range(r + 1, c + 1).Value2
                Next

            Next

			'add chart title
			chart.ChartTitle.TextProperties.Text = "Monthly Sales Report"
			chart.ChartTitle.TextProperties.IsCentered = True
            chart.ChartTitle.Height = 30
			chart.HasTitle = True

			'set the series label

            chart.Series.SeriesLabel = chart.ChartData("B1", "B1")

			'set the category labels

            chart.Categories.CategoryLabels = chart.ChartData("A2", "A13")

			'set the series values

            chart.Series(0).Values = chart.ChartData("B2", "B13")

			'save the file
			ppt.SaveToFile("chart.pptx", Spire.Presentation.FileFormat.Pptx2013)
		End Sub

    End Class
End Namespace
page 22