Thursday, 20 January 2011 10:33

Insert Image in Excel in C#, VB.NET

Users are allowed to insert image in Excel files. With image, the appearance of Excel file will be more beautiful. Besides decorating, some images are related to data information in Excel. For example, the image will be a chart. These images can make readers learn data information more clearly. This guide will show an easy method to insert image in Excel with C#, VB.NET

Spire.XLS for .NET, a professional component to operating Excel files, enables users to insert image in Excel by using C# and VB.NET. This guide focuses on how to easily insert image in Excel by using Spire.XLS for .NET.  Developers can use sheet.Pictures.Add(int toprow, int leftcolumn, filename string) method to insert image in Excel directly. Below demonstrates an Excel with an image of flower.

Insert Excel Image

Download and install Spire.XLS for .NET and then use the following code to insert image.

[C#]
using Spire.Xls;

namespace InsertImage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create Workbook
            Workbook workbook = new Workbook();
            Worksheet sheet = workbook.Worksheets[0];

            //Insert Image
            sheet.Pictures.Add(1, 1, @"E:\work\sample.jpg");

            //Save and Launch
            workbook.SaveToFile("ExcelImage.xlsx", ExcelVersion.Version2010);
            System.Diagnostics.Process.Start("ExcelImage.xlsx");
        }
    }
}
[VB.NET]
Imports Spire.Xls

Namespace InsertImage
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            'Create Workbook
            Dim workbook As New Workbook()
            Dim sheet As Worksheet = workbook.Worksheets(0)

            'Insert Image
            sheet.Pictures.Add(1, 1, "E:\work\sample.jpg")

            'Save and Launch
            workbook.SaveToFile("ExcelImage.xlsx", ExcelVersion.Version2010)
            System.Diagnostics.Process.Start("ExcelImage.xlsx")
        End Sub
    End Class
End Namespace
Thursday, 20 January 2011 10:26

Create Excel Pie Chart in C#, VB.NET

Why We Create Excel Pie Charts?

Create excel pie charts is a simple method to display your data to other individuals or a group. Excel pie charts can easily relay your messages that may otherwise go unnoticed by your audience. Pie charts are helpful for international audiences because they are universally known and easily explained. And it's extremely easy to create and use in Excel.

Pie charts, unlike other charts in Microsoft Excel, require the data in your worksheet be contained in only one row or column. By indicating a "category", an additional row or column can be used. Relative sizes are easy to compare as each piece of data is represented as a portion of a whole.

How to Create Excel Pie Charts in Microsoft Excel?

Every one of you can create excel pie charts in no time by using Microsoft Excel through the following steps:

  • Launch Microsoft Office Excel and open your excel file which with the data that you want to base your pie chart on.
  • Select the data that you want to base your chart on. The last cell that you want to select will not be chosen but it will have bold outline borders around it.
  • Click "Insert" button to open Chart Wizard window. Click on "Pie" in the right side column of Chart Type. Several sub-types of pie charts will be offered for you to choose. Pick a proper type which can best match with your data and click "Next"
  • Prevew on this new interface. If the pie chart with wrong information or even no pie chart appears, click "Cancel" and select your data, try the above process again. If everything is OK, click "Next"
  • On the new window, enter labels and a title for your pie chart. Click "Finish" when you see the pie chart appears as you want.
  • On your spreadsheet, click the box and drag your mouse to manipulate the size of the chart. By right clicking the chart and box, you can get many options to edit the pie chart.

How to Use Spire.XLS for .NET to Creat Excel Pie Charts?

Spire.XLS presents you an easy way to create a pie chart in the Excel workbook. First, you should create a pie chart with the sheet.Charts.Add method. You may control the resource of the data and title of the chart by setting DataRange and ChartTitle properties. What's more, we create an object to operate more about the chart. You may set the label and value of the pie with the properties cs.CategoryLabels and cs.Values. If you want to hide the value of the pie, you may set the cs.DataPoints.DefaultDataPoint.DataLabels.HasValue property false. In this demo, in order to reflect the effect of the chart, we set the grid lines of the worksheet invisible by assigning the sheet.GridLinesVisible false.

Use the C#/VB.NET codes of Spire.XLS for .NET below to create excel pie charts:

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

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

            //Initialize worksheet
            workbook.CreateEmptySheets(1);
            Worksheet sheet = workbook.Worksheets[0];

            //Set sheet name
            sheet.Name = "Chart data";

            //Set the grid lines invisible
            sheet.GridLinesVisible = false;

            //Create a chart
            Chart chart = sheet.Charts.Add(ExcelChartType.Pie3D);

            //Set region of chart data
            chart.DataRange = sheet.Range["B2:B5"];
            chart.SeriesDataFromRange = false;

            //Set position of chart
            chart.LeftColumn = 1;
            chart.TopRow = 6;
            chart.RightColumn = 9;
            chart.BottomRow = 25;

            //Chart title
            chart.ChartTitle = "Sales by year";
            chart.ChartTitleArea.IsBold = true;
            chart.ChartTitleArea.Size = 12;

            //Initialize the chart series
            Spire.Xls.Charts.ChartSerie cs = chart.Series[0];

            //Chart Labels resource
            cs.CategoryLabels = sheet.Range["A2:A5"];

            //Chart value resource
            cs.Values = sheet.Range["B2:B5"];

            //Set the value visible in the chart
            cs.DataPoints.DefaultDataPoint.DataLabels.HasValue = true;

            //Year
            sheet.Range["A1"].Value = "Year";
            sheet.Range["A2"].Value = "2002";
            sheet.Range["A3"].Value = "2003";
            sheet.Range["A4"].Value = "2004";
            sheet.Range["A5"].Value = "2005";

            //Sales
            sheet.Range["B1"].Value = "Sales";
            sheet.Range["B2"].NumberValue = 4000;
            sheet.Range["B3"].NumberValue = 6000;
            sheet.Range["B4"].NumberValue = 7000;
            sheet.Range["B5"].NumberValue = 8500;

            //Style
            sheet.Range["A1:B1"].Style.Font.IsBold = true;
            sheet.Range["A2:B2"].Style.KnownColor = ExcelColors.LightYellow;
            sheet.Range["A3:B3"].Style.KnownColor = ExcelColors.LightGreen1;
            sheet.Range["A4:B4"].Style.KnownColor = ExcelColors.LightOrange;
            sheet.Range["A5:B5"].Style.KnownColor = ExcelColors.LightTurquoise;

            //Border
            sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeTop].Color = Color.FromArgb(0, 0, 128);
            sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thin;
            sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeBottom].Color = Color.FromArgb(0, 0, 128);
            sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;
            sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeLeft].Color = Color.FromArgb(0, 0, 128);
            sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
            sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeRight].Color = Color.FromArgb(0, 0, 128);
            sheet.Range["A1:B5"].Style.Borders[BordersLineType.EdgeRight].LineStyle = LineStyleType.Thin;
            
            //Number format
            sheet.Range["B2:C5"].Style.NumberFormat = "\"$\"#,##0";           
            chart.PlotArea.Fill.Visible = false;
                  
            //Save the file
            workbook.SaveToFile("Sample.xls",ExcelVersion.Version97to2003);

            //Launch the file
            System.Diagnostics.Process.Start("Sample.xls");
        }
    }
[VB.NET]
Imports Spire.Xls
Imports System.Drawing

Module Module1

    Sub Main()
        'Create a new workbook
        Dim workbook As New Workbook()

        'Initialize worksheet
        workbook.CreateEmptySheets(1)
        Dim sheet As Worksheet = workbook.Worksheets(0)

        'Set sheet name
        sheet.Name = "Chart data"

        'Set the grid lines invisible
        sheet.GridLinesVisible = False

        'Create a chart
        Dim chart As Chart = sheet.Charts.Add(ExcelChartType.Pie3D)

        'Set region of chart data
        chart.DataRange = sheet.Range("B2:B5")
        chart.SeriesDataFromRange = False

        'Set position of chart
        chart.LeftColumn = 1
        chart.TopRow = 6
        chart.RightColumn = 9
        chart.BottomRow = 25

        'Chart title
        chart.ChartTitle = "Sales by year"
        chart.ChartTitleArea.IsBold = True
        chart.ChartTitleArea.Size = 12

        'Set the chart
        Dim cs As Spire.Xls.Charts.ChartSerie = chart.Series(0)

        'Chart Labels resource
        cs.CategoryLabels = sheet.Range("A2:A5")

        'Chart value resource
        cs.Values = sheet.Range("B2:B5")

        'Set the value visible in the chart
        cs.DataPoints.DefaultDataPoint.DataLabels.HasValue = True

        'Year
        sheet.Range("A1").Value = "Year"
        sheet.Range("A2").Value = "2002"
        sheet.Range("A3").Value = "2003"
        sheet.Range("A4").Value = "2004"
        sheet.Range("A5").Value = "2005"

        'Sales
        sheet.Range("B1").Value = "Sales"
        sheet.Range("B2").NumberValue = 4000
        sheet.Range("B3").NumberValue = 6000
        sheet.Range("B4").NumberValue = 7000
        sheet.Range("B5").NumberValue = 8500

        'Style
        sheet.Range("A1:B1").Style.Font.IsBold = True
        sheet.Range("A2:B2").Style.KnownColor = ExcelColors.LightYellow
        sheet.Range("A3:B3").Style.KnownColor = ExcelColors.LightGreen1
        sheet.Range("A4:B4").Style.KnownColor = ExcelColors.LightOrange
        sheet.Range("A5:B5").Style.KnownColor = ExcelColors.LightTurquoise

        'Border
        sheet.Range("A1:B5").Style.Borders(BordersLineType.EdgeTop).Color = Color.FromArgb(0, 0, 128)
        sheet.Range("A1:B5").Style.Borders(BordersLineType.EdgeTop).LineStyle = LineStyleType.Thin
        sheet.Range("A1:B5").Style.Borders(BordersLineType.EdgeBottom).Color = Color.FromArgb(0, 0, 128)
        sheet.Range("A1:B5").Style.Borders(BordersLineType.EdgeBottom).LineStyle = LineStyleType.Thin
        sheet.Range("A1:B5").Style.Borders(BordersLineType.EdgeLeft).Color = Color.FromArgb(0, 0, 128)
        sheet.Range("A1:B5").Style.Borders(BordersLineType.EdgeLeft).LineStyle = LineStyleType.Thin
        sheet.Range("A1:B5").Style.Borders(BordersLineType.EdgeRight).Color = Color.FromArgb(0, 0, 128)
        sheet.Range("A1:B5").Style.Borders(BordersLineType.EdgeRight).LineStyle = LineStyleType.Thin

        'Number format
        sheet.Range("B2:C5").Style.NumberFormat = """$""#,##0"
        chart.PlotArea.Fill.Visible = False

        'Save doc file.
        workbook.SaveToFile("Sample.xls",ExcelVersion.Version97to2003)

        'Launch the MS Word file.
        System.Diagnostics.Process.Start("Sample.xls")

    End Sub
End Module

After running the demo, you may find a pie appear in the document:

Generate Excel Pie Chart

Thursday, 20 January 2011 08:42

Create Word Table in C#, VB.NET

Word Table can save and display data to enable readers to get information more clearly. Users can insert table in Word document with specified rows, columns and format cells to have a good appearance. This guide introduces a solution to create Word table with data and format cells in C# and VB.NET via Spire.Doc for .NET. The screenshot below presents result after creating and formatting Word table.

Create Word Table

Spire.Doc for .NET, the professional .NET Word component to operate Word document, provides a Table class to perform tasks on table, for example, including rows, columns, cells and table layout operation. The following will show a specified example to create Word table step by step.

Download and install Spire.Doc for .NET at the beginning and follow steps.

  • Firstly, create a new Document class instance and add a new Section in this instance. Invoke Section.AddTable(bool ShowBorder) method to create a table with or without borders.
  • Secondly, initialize two String array instances, Header and data to fill table soon.
  • Thirdly, Invoke Table.ResetCells(int rowsNum, int columnsNum) method to reset rows and columns numbers.
  • Fourthly, fill and format data in table. Create header row at first. Initialize a TableRow instance FRow and set its IsHeader property as true, Height property as a float value and BackColor of RowFormat property as a specified color.
  • Use for loop to fill Header in this TableRow instance and format each cell. Set VerticalAlignment of CellFormat property of FRow.
  • Then, initialize a Paragraph instance p for Cells of FRow. Set HorizontalAlignment of Format property of p.
  • Next, Initialize a TextRange instance TR which stores String array Header.
  • Set CharacterFormat property, including FontName, FontSize, TextColor and Bold for TR.
  • Create data row now. Initialize another TableRow instance DataRow and set Height property.
  • Then, fill this instance with String array data and format cells as operating on FRow.
[C#]
using System;
using System.Data;
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace WordTable
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create Table
            Document doc = new Document();
            Section s = doc.AddSection();
            Table table =s.AddTable(true);

            //Create Header and Data
            String[] Header ={"Item","Description", "Qty","Unit Price","Price"};  
            String[][] data = {
                                  new String[]{ "Spire.Doc for .NET",".NET Word Component","1","$799.00","$799.00"},
                                  new String[]{"Spire.XLS for .NET",".NET Excel Component","2","$799.00","$1,598.00"},
                                  new String[]{"Spire.Office for .NET",".NET Office Component","1","$1,899.00","$1,899.00"},
                                  new String[]{"Spire.PDF for .NET",".NET PDFComponent","2","$599.00","$1,198.00"},
                              };
            //Add Cells
            table.ResetCells(data.Length + 1, Header.Length);

            //Header Row
            TableRow FRow= table.Rows[0];
            FRow.IsHeader = true;
            //Row Height
            FRow.Height = 23;
            //Header Format
            FRow.RowFormat.BackColor = Color.AliceBlue;
            for (int i = 0; i < Header.Length; i++)
            {
                //Cell Alignment
                Paragraph p = FRow.Cells[i].AddParagraph();
                FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                p.Format.HorizontalAlignment = HorizontalAlignment.Center;
                //Data Format
                TextRange TR = p.AppendText(Header[i]);
                TR.CharacterFormat.FontName = "Calibri";
                TR.CharacterFormat.FontSize = 14;
                TR.CharacterFormat.TextColor = Color.Teal;
                TR.CharacterFormat.Bold = true;
            }

            //Data Row
            for (int r = 0; r < data.Length; r++)
            {
                TableRow DataRow = table.Rows[r + 1];

                //Row Height
                DataRow.Height = 20;

                //C Represents Column.
                for (int c = 0; c < data[r].Length; c++)
                {
                    //Cell Alignment
                    DataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                    //Fill Data in Rows
                    Paragraph p2 =DataRow.Cells[c].AddParagraph();
                    TextRange TR2=p2.AppendText(data[r][c]);
                    //Format Cells
                    p2.Format.HorizontalAlignment = HorizontalAlignment.Center;
                    TR2.CharacterFormat.FontName = "Calibri";
                    TR2.CharacterFormat.FontSize = 12;
                    TR2.CharacterFormat.TextColor = Color.Brown;
                }
            }

            //Save and Launch
            doc.SaveToFile("WordTable.docx",FileFormat.docx2013);
            System.Diagnostics.Process.Start("WordTable.docx");
        }
    }
}
[VB.NET]
Imports System
Imports System.Data
Imports System.Drawing
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields

Namespace WordTable
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            'Create Table
            Dim doc As New Document()
            Dim s As Section = doc.AddSection()
            Dim table As Table = s.AddTable(True)

            'Create Header and Data
            Dim Header() As String = {"Item", "Description", "Qty", "Unit Price", "Price"}
            Dim data()() As String = {New String() {"Spire.Doc for .NET", ".NET Word Component", "1", "$799.00", "$799.00"},
                                      New String() {"Spire.XLS for .NET", ".NET Excel Component", "2", "$799.00", "$1,598.00"},
                                      New String() {"Spire.Office for .NET", ".NET Office Component", "1", "$1,899.00", "$1,899.00"},
                                      New String() {"Spire.PDF for .NET", ".NET PDFComponent", "2", "$599.00", "$1,198.00"}}
            'Add Cells
            table.ResetCells(data.Length + 1, Header.Length)

            'Header Row
            Dim FRow As TableRow = table.Rows(0)
            FRow.IsHeader = True
            'Row Height
            FRow.Height = 23
            'Header Format
            FRow.RowFormat.BackColor = Color.AliceBlue
            For i As Integer = 0 To Header.Length - 1
                'Cell Alignment
                Dim p As Paragraph = FRow.Cells(i).AddParagraph()
                FRow.Cells(i).CellFormat.VerticalAlignment = VerticalAlignment.Middle
                p.Format.HorizontalAlignment = HorizontalAlignment.Center
                'Data Format
                Dim TR As TextRange = p.AppendText(Header(i))
                TR.CharacterFormat.FontName = "Calibri"
                TR.CharacterFormat.FontSize = 14
                TR.CharacterFormat.TextColor = Color.Teal
                TR.CharacterFormat.Bold = True
            Next i

            'Data Row
            For r As Integer = 0 To data.Length - 1
                Dim DataRow As TableRow = table.Rows(r + 1)

                'Row Height
                DataRow.Height = 20

                'C Represents Column.
                For c As Integer = 0 To data(r).Length - 1
                    'Cell Alignment
                    DataRow.Cells(c).CellFormat.VerticalAlignment = VerticalAlignment.Middle
                    'Fill Data in Rows
                    Dim p2 As Paragraph = DataRow.Cells(c).AddParagraph()
                    Dim TR2 As TextRange = p2.AppendText(data(r)(c))
                    'Format Cells
                    p2.Format.HorizontalAlignment = HorizontalAlignment.Center
                    TR2.CharacterFormat.FontName = "Calibri"
                    TR2.CharacterFormat.FontSize = 12
                    TR2.CharacterFormat.TextColor = Color.Brown
                Next c
            Next r

            'Save and Launch
            doc.SaveToFile("WordTable.docx",FileFormat.docx2013);
            System.Diagnostics.Process.Start("WordTable.docx")
        End Sub
    End Class
End Namespace

Spire.Doc, an easy-to-use component to operate Word document, allows developers to fast generate, write, edit and save Word (Word 97-2003, Word 2007, Word 2010) in C# and VB.NET for .NET, Silverlight and WPF.

Wednesday, 19 January 2011 06:50

Create Excel Group in C#, VB.NET

Excel group separate data in Excel worksheet into several groups. Each group may present information of one item. For example, there is a worksheet about sales information about several kinds of products. Users can collect one kind of product in a group to distinguish products type.

Spire.XLS for .NET, an easy-to-use component to manipulate Microsoft Excel workbooks, enables users to create Excel group by using C#, VB.NET. This guide will show the easiest method to realize this function via Spire.XLS for .NET.

Download and install Spire.XLS for .NET. Then invoke sheet.GroupByRows(int firstRow, int lastRow, bool isCollapsed) method to create Excel group by rows. If you want to create group by columns, invoke sheet.GroupByColumns() method directly. After running, you can get the following result:

Create Excel Group

[C#]
using Spire.Xls;

namespace ExcelGroup
{
    class Group
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"E:\Work\Documents\ExcelFiles\PartSalesInfo.xlsx");
            Worksheet sheet = workbook.Worksheets[0];

            sheet.GroupByRows(2, 9, true);

            workbook.SaveToFile("Group.xlsx", ExcelVersion.Version2010);
            System.Diagnostics.Process.Start("Group.xlsx");
        }
    }
}
[VB.NET]
Imports Spire.Xls

Namespace ExcelGroup
	Friend Class Group
		Shared Sub Main(ByVal args() As String)
			Dim workbook As New Workbook()
			workbook.LoadFromFile("E:\Work\Documents\ExcelFiles\PartSalesInfo.xlsx")
			Dim sheet As Worksheet = workbook.Worksheets(0)

			sheet.GroupByRows(2, 9, True)

			workbook.SaveToFile("Group.xlsx", ExcelVersion.Version2010)
			System.Diagnostics.Process.Start("Group.xlsx")
		End Sub
	End Class
End Namespace
Wednesday, 19 January 2011 06:38

Set Word Indent in C#, VB.NET

Word Indent, a kind of paragraph format, is used to adjust distance between paragraph body and page margins. It includes left indent, right indent, first line indent and hanging indent. Frist indent and right indent can be applied for all paragraph body, while first line indent just can be used for first line of one paragraph and hanging indent for paragraph body except the first line. This guide introduces a solution to set Word indent in C# and VB.NET via Spire.Doc for .NET. The following screenshot presents result after setting indents.

Word Paragraph Indent

Spire.Doc for .NET, powerful .NET Word component, provides a ParagraphFormat class to enables users to set format for specified paragraph and indents are format properties of ParagraphFormat class. Firstly, get specified paragraphs to set indents in document. Secondly, set LeftIndent, RightIndent, FirstLineIndent properties for these paragraphs. Please note that type of all indent properties is float. Download and install Spire.Doc for .NET and follow the code blow to set Word indents.

[C#]
using Spire.Doc;
using Spire.Doc.Documents;

namespace WordIndent
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile(@"E:\Work\Documents\WordDocuments\Microsoft Word 2013 Preview.docx");

            Paragraph para1 = doc.Sections[0].Paragraphs[0];
            para1.Format.LeftIndent = 30;

            Paragraph para2 = doc.Sections[0].Paragraphs[2];
            para2.Format.FirstLineIndent = 30;

            Paragraph para3 = doc.Sections[0].Paragraphs[4];
            para3.Format.RightIndent = 80;

            doc.SaveToFile("Indent.docx", FileFormat.Docx2010);
            System.Diagnostics.Process.Start("Indent.docx");
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace WordIndent
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            Dim doc As New Document()
            doc.LoadFromFile("E:\Work\Documents\WordDocuments\Microsoft Word 2013 Preview.docx")

            Dim para1 As Paragraph = doc.Sections(0).Paragraphs(0)
            para1.Format.LeftIndent = 30

            Dim para2 As Paragraph = doc.Sections(0).Paragraphs(2)
            para2.Format.FirstLineIndent = 30

            Dim para3 As Paragraph = doc.Sections(0).Paragraphs(4)
            para3.Format.RightIndent = 80

            doc.SaveToFile("Indent.docx", FileFormat.Docx2010)
            System.Diagnostics.Process.Start("Indent.docx")
        End Sub
    End Class
End Namespace

Spire.Doc, specializing in manipulating Word document, enables users to generate, write, modify and save Word document (.doc/.docx) quickly and easily in .NET, Silverlight and WPF with C# and VB.NET.

Word Page Break, a mark to present ending of one page and beginning of new page, can be inserted automatically when users fill one page with contents or manually at a specified location by users. This guide demonstrates an easy solution to insert page break to split one page contents into two pages in C#, VB.NET via Spire.Doc for .NET. The following screenshot shows result after inserting Word page break.

Word Page Breaks

Spire.Doc for .NET provides Paragraph.AppendBreak method with customers to insert break easily in Word. The overload, which should be passed to this method, is BreakType (enum-type). There are three break types offered by Spire.Doc for .NET, PageBreak, ColumnBreak and LineBreak. Download and install Spire.Doc for .NET and follow the code blow to insert Word page break behind the specified paragraph.

[C#]
using Spire.Doc;
using Spire.Doc.Documents;

namespace WordBreak
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile(@"E:\Work\Documents\WordDocuments\.NET Framework.docx");

            document.Sections[0].Paragraphs[3].AppendBreak(BreakType.PageBreak);

            document.SaveToFile("PageBreak.docx", FileFormat.Docx2010);
            System.Diagnostics.Process.Start("PageBreak.docx");
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace WordBreak
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            Dim document As New Document()
            document.LoadFromFile("E:\Work\Documents\WordDocuments\.NET Framework.docx")

            document.Sections(0).Paragraphs(3).AppendBreak(BreakType.PageBreak)

            document.SaveToFile("PageBreak.docx", FileFormat.Docx2010)
            System.Diagnostics.Process.Start("PageBreak.docx")
        End Sub
    End Class
End Namespace

Spire.Doc, a professional Word component, enables developers/programmers perform a wide range of processing tasks, such as generate, write, modify and save for their customize .NET, Silverlight and WPF applications.

Tuesday, 18 January 2011 05:53

Insert Word Comment in C#, VB.NET

Word comment, inserted by users to show opinions or additional information about words, phrases or paragraphs, is often appeared in the document margins. According to comments, readers can learn some more information about contents or modify contents to express own thoughts more correctly or clearly.

Spire.Doc for .NET, a professional .NET Word component to manipulate Word documents, enables users to insert comment in Word with C#, VB.NET. Users can invoke paragraph.AppendComment(string) method to insert comment for specified paragraph directly. Also, Spire.Doc for .NET provides a Comment class with users. Users can use Format property offered this class to set format comment.

The following demonstrates how perfect a comment can be. You can also freely download Spire.Doc and have a trial.

Insert Word Comment

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace InsertComment
{
    class Program
    {

        static void Main(string[] args)
        {

            //Load Document
            Document document = new Document();
            document.LoadFromFile(@"E:\work\Documents\WordDocuments\Humor Them.docx");

            //Get Paragraph to Insert Comment
            Section section = document.Sections[0];
            Paragraph paragraph = section.Paragraphs[2];

            //Insert Comment
            string str = "This paragraph presents the first example to Humor Them.";
            Comment comment = paragraph.AppendComment(str);
            comment.Format.Author = "E-iceblue";
            comment.Format.Initial = "CM";

            //Save Document
            document.SaveToFile("comments.docx", FileFormat.Docx2010);
            System.Diagnostics.Process.Start("comments.docx");
        }
    }
}

 

[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Namespace InsertComment
	Class Program

		Private Shared Sub Main(args As String())

			'Load Document
			Dim document As New Document()
			document.LoadFromFile("E:\work\Documents\WordDocuments\Humor Them.docx")

			'Get Paragraph to Insert Comment
			Dim section As Section = document.Sections(0)
			Dim paragraph As Paragraph = section.Paragraphs(2)

			'Insert Comment
			Dim str As String = "This paragraph presents the first example to Humor Them."
			Dim comment As Comment = paragraph.AppendComment(str)
			comment.Format.Author = "E-iceblue"
			comment.Format.Initial = "CM"

			'Save Document
			document.SaveToFile("comments.docx", FileFormat.Docx2010)
			System.Diagnostics.Process.Start("comments.docx")
		End Sub
	End Class
End Namespace

Spire.Doc is a Microsoft Word component, which enables users to perform a wide range of Word document processing tasks directly, such as generate, read, write and modify Word document in WPF, .NET and Silverlight.

Tuesday, 18 January 2011 04:01

Decrypt Word Document in C#, VB.NET

Word Decryption is a process to decode encrypted Word document. It requires a password or secret key. If readers want to open and read a protected Word, they need to decrypt this Word document firstly. This guide demonstrates an easy and convenient solution to decrypt Word in C# and VB.NET via Spire.Doc for .NET.

Spire.Doc for .NET, specially developed for programmers to manipulate Word without Word Automation, provides users a method Document.LoadFromFile(String fileName, FileFormat fileFormat, String password) of Document class to open encrypted Word document. It also provides another method Document.RemoveEncryption() to decrypt Word without any protection. Through these two methods, users can decrypt Word easily with Spire.Doc for .NET. Download and install Spire.Doc for .NET. Then follow the code to decrypt.

[C#]
using Spire.Doc;

namespace DecryptWord
{
    class Decryption
    {
        static void Main(string[] args)
        {
            //Load Encrypted Word
            Document document = new Document();
            document.LoadFromFile(@"E:\Work\Documents\Student Transcript.docx", FileFormat.Docx,"123456");

            //Decrypt
            document.RemoveEncryption();
            
            //Save and Launch
            document.SaveToFile("decryption.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("decryption.docx");
        }
    }
}
[VB.NET]
Imports Spire.Doc

Namespace DecryptWord
    Friend Class Decryption
        Shared Sub Main(ByVal args() As String)
            'Load Encrypted Word
            Dim document As New Document()
            document.LoadFromFile("E:\Work\Documents\Student Transcript.docx", FileFormat.Docx, "123456")

            'Decrypt
            document.RemoveEncryption()

            'Save and Launch
            document.SaveToFile("decryption.docx", FileFormat.Docx)
            System.Diagnostics.Process.Start("decryption.docx")
        End Sub
    End Class
End Namespace

Spire.Doc, professional Word component, is specially designed for developers to fast generate, write, modify and save Word documents in .NET, Silverlight and WPF with C# and VB.NET. Also, it supports conversion between Word and other popular formats, such as PDF, HTML, Image, Text and so on, in .NET and WPF platform.

Tuesday, 18 January 2011 02:22

How to Convert Word to PDF

This is an all-in-one solution to convert Word to PDF. Within this solution, you can either create a word from scratch or load a word template from folder, and then edit the document as you like; finally you can effortlessly convert word to PDF in C#, VB.NET. The conversion can be doc to PDF or docx to PDF.

Spire.Doc for .NET is a professional .NET library which enables users to directly manage word editing without Microsoft Word being installed, after the editing, you can convert the document to PDF in 2 steps.

Below is the an effective screenshot of the document which will be converted to PDF, at the end Of this post, you can find the target PDF.

Word to PDF

Now feel free to download Spire.Doc for .NET and convert word to PDF for personal use or evaluation. The whole process of converting word to PDF in C#, VB.NET can be described as 2 simple steps.

1. Declare a document and load document which you prepare by using ocument.LoadFromFile() method. The parameter passed to this method is file name string.

2. Save Word document as PDF by using document.SaveToFile() method. Parameters passed to this method is file name string and file format. The file format must be PDF.

[C#]
using System;
using Spire.Doc;
using Spire.Doc.Documents;

namespace DoctoPDF
{
    class toPDF
    {
        static void Main(string[] args)
        {
            //Load Document
            Document document = new Document();
            document.LoadFromFile(@"E:\work\documents\TestSample.docx");

            //Convert Word to PDF
            document.SaveToFile("toPDF.PDF", FileFormat.PDF);

            //Launch Document
            System.Diagnostics.Process.Start("toPDF.PDF");
        }
    }
}
[VB.NET]
Imports System
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace DoctoPDF
    Friend Class toPDF
        Shared Sub Main(ByVal args() As String)
            'Load Document
            Dim document As New Document()
            document.LoadFromFile("E:\work\documents\TestSample.docx")

            'Convert Word to PDF
            document.SaveToFile("toPDF.PDF", FileFormat.PDF)

            'Launch Document
            System.Diagnostics.Process.Start("toPDF.PDF")
        End Sub
    End Class
End Namespace

After running the demo, you may find a PDF document launched on your computer:

Word to PDF

Spire.Doc is an MS Word component which enables user to perform a wide range of Word document processing tasks directly, such as generate, read, write and modify Word document for .NET and Silverlight.

More about This .NET Word component

Thursday, 13 January 2011 09:49

Insert Image Header and Footer for Word

Word header and footer presents additional information of Word document, which can be text, image or page number. This guide focuses on introducing how to insert image header and footer for Word document in C# and VB.NET.

Header/Footer plays an important role in Word document, which uses text, image or page number to demonstrate some additional information about this document. The information can be company name, logo, author name, document title etc. This guide will demonstrate detailed process to insert image header/footer in Word with C# and VB.NET via Spire.Doc for .NET. The following screenshot displays Word image header/footer result after programming.

Insert Image Header/Footer

Spire.Doc for .NET provides a HeaderFooter. class to enable developers to generate a new header or footer. Firstly, initialize a header instance of HeaderFooter class and then invoke AddParagraph() method to add a paragraph body for this header/footer instance. Next, invoke Paragraph.AppendPicture(Image image) method to append a picture for header/footer paragraph. If you want to add text for paragraph as well, please invoke Paragraph.AppendText(string text) method. Also, you can set format for header/footer paragraph, appended image and text to have a better layout. Code as following:

[C#]
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace ImageHeaderFooter
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load Document
            Document document = new Document();
            document.LoadFromFile(@"E:\Work\Documents\Spire.Doc for .NET.docx");

            //Initialize a Header Instance
            HeaderFooter header = document.Sections[0].HeadersFooters.Header;
            //Add Header Paragraph and Format 
            Paragraph paragraph = header.AddParagraph();
            paragraph.Format.HorizontalAlignment = HorizontalAlignment.Right;
            //Append Picture for Header Paragraph and Format
            DocPicture headerimage = paragraph.AppendPicture(Image.FromFile(@"E:\Logo\doclog.png"));
            headerimage.VerticalAlignment = ShapeVerticalAlignment.Bottom;

            //Initialize a Footer Instance
            HeaderFooter footer = document.Sections[0].HeadersFooters.Footer;
            //Add Footer Paragraph and Format
            Paragraph paragraph2 = footer.AddParagraph();
            paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Left;
            //Append Picture and Text for Footer Paragraph
            DocPicture footerimage = paragraph2.AppendPicture(Image.FromFile(@"E:\Logo\logo.jpeg"));
            TextRange TR = paragraph2.AppendText("Copyright © 2013 e-iceblue. All Rights Reserved.");
            TR.CharacterFormat.FontName = "Arial";
            TR.CharacterFormat.FontSize = 10;
            TR.CharacterFormat.TextColor = Color.Black;

            //Save and Launch
            document.SaveToFile("ImageHeaderFooter.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("ImageHeaderFooter.docx");
        }
    }
}
[VB.NET]
Imports System.Drawing
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields

Namespace ImageHeaderFooter
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            'Load Document
            Dim document As New Document()
            document.LoadFromFile("E:\Work\Documents\Spire.Doc for .NET.docx")

            'Initialize a Header Instance
            Dim header As HeaderFooter = document.Sections(0).HeadersFooters.Header
            'Add Header Paragraph and Format 
            Dim paragraph As Paragraph = header.AddParagraph()
            paragraph.Format.HorizontalAlignment = HorizontalAlignment.Right
            'Append Picture for Header Paragraph and Format
            Dim headerimage As DocPicture = paragraph.AppendPicture(Image.FromFile("E:\Logo\doclog.png"))
            headerimage.VerticalAlignment = ShapeVerticalAlignment.Bottom

            'Initialize a Footer Instance
            Dim footer As HeaderFooter = document.Sections(0).HeadersFooters.Footer
            'Add Footer Paragraph and Format
            Dim paragraph2 As Paragraph = footer.AddParagraph()
            paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Left
            'Append Picture and Text for Footer Paragraph
            Dim footerimage As DocPicture = paragraph2.AppendPicture(Image.FromFile("E:\Logo\logo.jpeg"))
            Dim TR As TextRange = paragraph2.AppendText("Copyright © 2013 e-iceblue. All Rights Reserved.")
            TR.CharacterFormat.FontName = "Arial"
            TR.CharacterFormat.FontSize = 10
            TR.CharacterFormat.TextColor = Color.Black

            'Save and Launch
            document.SaveToFile("ImageHeaderFooter.docx", FileFormat.Docx)
            System.Diagnostics.Process.Start("ImageHeaderFooter.docx")
        End Sub
    End Class
End Namespace

Spire.Doc, an easy-to-use component to perform Word tasks, allows developers to fast generate, write, edit and save Word (Word 97-2003, Word 2007, Word 2010) in C# and VB.NET for .NET, Silverlight and WPF.