Wrap text and unwrap text in excel cells are indispensable for developers. Wrap text is specially required when the excel text exceeds the column width or excel data cannot be shown completely. While unwrap text enables the cell data to be displayed in orderly rows and columns. In this section, a solution will be introduced for you to quickly wrap or unwrap text in excel with C#, VB.NET via a .NET Excel component.

Spire.XLS for .NET, as a standalone excel component, can help both enterprises and individuals to operate a wide range of tasks in Excel document such as convert excel to other formats, encrypt/decrypt excel, generate different kinds of charts and tables etc. Using this Excel component, you can easily wrap and unwrap through two lines of core code.

Suppose you want to wrap text in A1, you can set up the A1 cell text and wrap properties by Worksheet. Range["A1"].Text and Worksheet.Range["A1"].Style.WrapText = true. Of course if you want to unwrap text in A1, you can set the wrap property to be false. Now, please download Spire.XLS for .NET and preview the effect of your text wrap and unwrap task as below picture.

Wrap and Unwrap Excel Data

[C#]
using Spire.Xls;

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


            //Wrap the excel text;
            sheet.Range["C1"].Text = "e-iceblue is in facebook and welcome to like us";
            sheet.Range["C1"].Style.WrapText = true;
            sheet.Range["D1"].Text = "e-iceblue is in twitter and welcome to follow us";
            sheet.Range["D1"].Style.WrapText=  true;


            //Unwrap the excel text;
            sheet.Range["C2"].Text = "http://www.facebook.com/pages/e-iceblue/139657096082266";
            sheet.Range["C2"].Style.WrapText= false;
            sheet.Range["D2"].Text = "https://twitter.com/eiceblue";
            sheet.Range["D2"].Style.WrapText = false;


            //set the text color of Range["C1:D1"]
            sheet.Range["C1:D1"].Style.Font.Size = 15;
            sheet.Range["C1:D1"].Style.Font.Color = Color.Blue;
            //set the text color of Range["C2:D2"]
            sheet.Range["C2:D2"].Style.Font.Size = 15;
            sheet.Range["C2:D2"].Style.Font.Color = Color.DeepSkyBlue;

            // Save the project;
            workbook.SaveToFile("sample.xls", ExcelVersion.Version97to2003);
            System.Diagnostics.Process.Start(workbook.FileName);

        }
    }
}
[VB.NET]
Imports Spire.Xls

Namespace wrap
    
    Class Program
        
        Private Shared Sub Main(ByVal args() As String)
            'Create a new workbook;
            Dim workbook As Workbook = New Workbook
            Dim sheet As Worksheet = workbook.Worksheets(0)
            'Wrap the excel text;
            sheet.Range("C1").Text = "e-iceblue is in facebook and welcome to like us"
            sheet.Range("C1").Style.WrapText = true
            sheet.Range("D1").Text = "e-iceblue is in twitter and welcome to follow us"
            sheet.Range("D1").Style.WrapText = true
            'Unwrap the excel text;
            sheet.Range("C2").Text = "http://www.facebook.com/pages/e-iceblue/139657096082266"
            sheet.Range("C2").Style.WrapText = false
            sheet.Range("D2").Text = "https://twitter.com/eiceblue"
            sheet.Range("D2").Style.WrapText = false
            'set the text color of Range["C1:D1"]
            sheet.Range("C1:D1").Style.Font.Size = 15
            sheet.Range("C1:D1").Style.Font.Color = Color.Blue
            'set the text color of Range["C2:D2"]
            sheet.Range("C2:D2").Style.Font.Size = 15
            sheet.Range("C2:D2").Style.Font.Color = Color.DeepSkyBlue
            ' Save the project;
            workbook.SaveToFile("sample.xls", ExcelVersion.Version97to2003)
            System.Diagnostics.Process.Start(workbook.FileName)
        End Sub
    End Class
End Namespace

Excel comment is added especially when the cell information is changed or need some additional notice. When we manually add comments in excel, it is such easy. While how about add excel comments programmatically? Could we set excel comment format in C#, VB.NET? The answer is absolutely YES. Now let us go to the main solution.

Excel comment will be quickly added as a string by this .NET Excel component Spire.XLS for .NET. Then, using ExcelFont which is a class in Spire.Xls, we can set comment format such as font, color, bold. In order to fit the comment perfectly, we can use another class Spire.Xls.RichText to set the text box size. Finally, when we want to highlight the special text in comment we can call this method: ExcelComment.RichText.SetFont(int startPos, int endPos, ExcelFont font). Now please see the comment effect as below picture:

Add Excel Comments

Here you can download Spire.XLS for .NET and install it on your system. After adding Spire.Xls dll, you can follow below solution to add comments in Excel.

[C#]
String str = "E-mail has been changed as evanece@hotmail.com";
            ExcelFont font1 = workbook.CreateFont();
            font1.FontName = "Calibri";
            font1.Color = Color.Firebrick;
            font1.IsBold = true;
            sheet.Range["C6"].Comment.RichText.Text = str;
            sheet.Range["C6"].Comment.Width = 200;
            sheet.Range["C6"].Comment.Height = 50;
            sheet.Range["C6"].Comment.RichText.SetFont(26, 45, font1);
[VB.NET]
Dim str As String = "E-mail has been changed as evanece@hotmail.com"
Dim font1 As ExcelFont = workbook.CreateFont()
font1.FontName = "Calibri"
font1.Color = Color.Firebrick
font1.IsBold = True
sheet.Range("C6").Comment.RichText.Text = str
sheet.Range("C6").Comment.Width = 200
sheet.Range("C6").Comment.Height = 50
sheet.Range("C6").Comment.RichText.SetFont(26, 45, font1)
Friday, 23 March 2012 02:30

How to Convert Word to Tiff

TIFF (Tagged Image File Format) is a flexible file format that is used to store images, including photos and art images. It’s popular and widely supported by image-manipulation applications, publishing and page layout applications, and scanning, faxing, word processing applications, etc. It can be a container holding compressed (lossy) JPEG and (lossless) PackBits compressed images. The ability to store image data in a lossless format makes a TIFF file to be a useful image archive. Therefore, sometimes developers need to convert documents in other formats (such as word) to TIFF format.

Spire.Doc, a powerful .NET word component which enables developers to convert files from word to TIFF easily. This article is going to introduce you the solution of converting word to TIFF by using Spire.Doc.

Note: before start, please download the latest version of Spire.Doc, then add the .dll in the bin folder as the reference of Visual Studio.

The sample word file:

How to Convert Word to Tiff

Follow the detail steps below:

Step 1: create a new document instance and load a word document from file.

Document document = new Document(@"E:\Program Files\testing.docx");

Step 2: use document.SaveToImages() method to save the word document as Image array.

private static Image[] SaveAsImage(Document document)
{     
    Image[] images = document.SaveToImages(ImageType.Bitmap);    
    return images;
}

Step 3: use JoinTiffImages() method to save the images from word pages to tiff image type, with the specified encoder and image-encoder parameters.

public static void JoinTiffImages(Image[] images, string outFile, EncoderValue compressEncoder)
{
    //use the save encoder
    System.Drawing.Imaging.Encoder enc = System.Drawing.Imaging.Encoder.SaveFlag;
    EncoderParameters ep = new EncoderParameters(2);
    ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
    ep.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)compressEncoder);
    Image pages = images[0];
    int frame = 0;
    ImageCodecInfo info = GetEncoderInfo("image/tiff");
    foreach (Image img in images)
    {
        if (frame == 0)
        {
            pages = img;
            //save the first frame
            pages.Save(outFile, info, ep);
        }
        else
        {
            //save the intermediate frames
            ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);
            pages.SaveAdd(img, ep);
        }
        if (frame == images.Length - 1)
        {
            //flush and close.
            ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
            pages.SaveAdd(ep);
        }
        frame++;
    }
}

The result TIFF file:

How to Convert Word to Tiff

Full codes:

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

namespace convert_word_to_tiff
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document(@"E:\Program Files\testing.docx");
            JoinTiffImages(SaveAsImage(document),"6056result.tiff",EncoderValue.CompressionLZW);
            System.Diagnostics.Process.Start("6056result.tiff");
        }
        private static Image[] SaveAsImage(Document document)
        {     
            Image[] images = document.SaveToImages(ImageType.Bitmap);    
            return images;
        }

        private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
            for (int j = 0; j < encoders.Length; j++)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            throw new Exception(mimeType + " mime type not found in ImageCodecInfo");
        }

        public static void JoinTiffImages(Image[] images, string outFile, EncoderValue compressEncoder)
        {
            //use the save encoder
            System.Drawing.Imaging.Encoder enc = System.Drawing.Imaging.Encoder.SaveFlag;
            EncoderParameters ep = new EncoderParameters(2);
            ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
            ep.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)compressEncoder);
            Image pages = images[0];
            int frame = 0;
            ImageCodecInfo info = GetEncoderInfo("image/tiff");
            foreach (Image img in images)
            {
                if (frame == 0)
                {
                    pages = img;
                    //save the first frame
                    pages.Save(outFile, info, ep);
                }

                else
                {
                    //save the intermediate frames
                    ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);

                    pages.SaveAdd(img, ep);
                }
                if (frame == images.Length - 1)
                {
                    //flush and close.
                    ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
                    pages.SaveAdd(ep);
                }
                frame++;
            }
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Drawing
Imports System.Drawing.Imaging

Namespace convert_word_to_tiff
	Class Program
		Private Shared Sub Main(args As String())
			Dim document As New Document("E:\Program Files\testing.docx")
			JoinTiffImages(SaveAsImage(document), "6056result.tiff", EncoderValue.CompressionLZW)
			System.Diagnostics.Process.Start("6056result.tiff")
		End Sub
		Private Shared Function SaveAsImage(document As Document) As Image()
			Dim images As Image() = document.SaveToImages(ImageType.Bitmap)
			Return images
		End Function

		Private Shared Function GetEncoderInfo(mimeType As String) As ImageCodecInfo
			Dim encoders As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders()
			For j As Integer = 0 To encoders.Length - 1
				If encoders(j).MimeType = mimeType Then
					Return encoders(j)
				End If
			Next
			Throw New Exception(mimeType & Convert.ToString(" mime type not found in ImageCodecInfo"))
		End Function

		Public Shared Sub JoinTiffImages(images As Image(), outFile As String, compressEncoder As EncoderValue)
			'use the save encoder
			Dim enc As System.Drawing.Imaging.Encoder = System.Drawing.Imaging.Encoder.SaveFlag
			Dim ep As New EncoderParameters(2)
			ep.Param(0) = New EncoderParameter(enc, CLng(EncoderValue.MultiFrame))
			ep.Param(1) = New EncoderParameter(System.Drawing.Imaging.Encoder.Compression, CLng(compressEncoder))
			Dim pages As Image = images(0)
			Dim frame As Integer = 0
			Dim info As ImageCodecInfo = GetEncoderInfo("image/tiff")
			For Each img As Image In images
				If frame = 0 Then
					pages = img
					'save the first frame
					pages.Save(outFile, info, ep)
				Else

					'save the intermediate frames
					ep.Param(0) = New EncoderParameter(enc, CLng(EncoderValue.FrameDimensionPage))

					pages.SaveAdd(img, ep)
				End If
				If frame = images.Length - 1 Then
					'flush and close.
					ep.Param(0) = New EncoderParameter(enc, CLng(EncoderValue.Flush))
					pages.SaveAdd(ep)
				End If
				frame += 1
			Next
		End Sub
	End Class
End Namespace

Spire.Doc can convert Word to most of popular file formats. It can convert Word to PDF, HTML, XML, RTF, Text, ePub, etc. Click to learn more

Wednesday, 21 March 2012 09:41

Set PDF Page Orientation in Silverlight

The sample demonstrates how to set PDF page orientation for Silverlight via Spire.PDF.

 

Wednesday, 21 March 2012 09:36

Lock Worksheet in Silverlight

The sample demonstrates how to Lock Worksheet in Silverlight via Spire.XLS.

 

Wednesday, 21 March 2012 09:29

Insert Comments into Word in Silverlight

The sample demonstrates how to insert comments into Word for Silverlight via Spire.Doc.

 

Tuesday, 20 March 2012 05:20

Set Excel Properties in C#, VB.NET

Excel Properties, which can be taken as metadata, present details of one file, including title, author, subject etc. Users can change properties according to data information, for example, adding key words or category for the file. But some properties are read-only, such as file size, created date, location and so on.

Spire.XLS for .NET, a professional component to manipulate Excel files, enables users to set Excel properties by using C#, VB.NET. This guide focuses on introducing method to set properties for Excel file.

Set Excel Properties

Users can set DocumentProperties property of Workbook class to change Excel properties as they want. The following screenshot shows properties after changing. Download and install Spire.XLS for .NET and use the following code to set Excel properties.

[C#]
workbook.DocumentProperties.Author = "E-iceblue Support Team";
workbook.DocumentProperties.Title = "Excel Properties";
workbook.DocumentProperties.Keywords = "Excel Properties C#, Excel Properties VB.NET";
workbook.DocumentProperties.Category = "Excel Demo";
workbook.DocumentProperties.Company = "E-iceblue";
[VB.NET]
workbook.DocumentProperties.Author = "E-iceblue Support Team"
workbook.DocumentProperties.Title = "Excel Properties"
workbook.DocumentProperties.Keywords = "Excel Properties C#, Excel Properties VB.NET"
workbook.DocumentProperties.Category = "Excel Demo"
workbook.DocumentProperties.Company = "E-iceblue"
Monday, 19 March 2012 06:55

Merge Excel Files into One in C#, VB.NET

Sometimes, people feel annoyed when they have to open a lot of Excel files simultaneously. Thus, Merging Excel files of the same type or category can help us avoid the trouble and save us much time. Besides, we would also like to merge multiple files in a single file for easy sharing and saving.

In the following section, an easy method is introduced to show how users can merge Excel files into one using Spire.XLS in C# and VB.NET.

Code Snippet:

Step 1: Create a new Workbook and remove the blank worksheets.

Workbook newbook = new Workbook();
newbook.Version = ExcelVersion.Version2010;
newbook.Worksheets.Clear();

Step 2: Create a temporary Workbook and load the sample files that you want to merge. Traversal every worksheet in tempbook, and add the copy of each worksheet to the new Workbook using AddCopy() method. By doing so, all the worksheets in the sample files will be added to the new Workbook.

Workbook tempbook = new Workbook();
string[] excelFiles = new String[] { "sample1.xlsx", "sample2.xlsx", "sample3.xlsx" };
for (int i = 0; i < excelFiles.Length; i++)
{
    tempbook.LoadFromFile(excelFiles[i]);
    foreach (Worksheet sheet in tempbook.Worksheets)
    {
        newbook.Worksheets.AddCopy(sheet);
    }
}

Step 3: Save the changes to the new Workbook and launch the file.

newbook.SaveToFile("result.xlsx", ExcelVersion.Version2010);
System.Diagnostics.Process.Start("result.xlsx");  

Output:

Each sample file only contains one worksheet in its workbook, therefore there would be three sheets in the result file.

Merge Excel Files into One in C#, VB.NET

Full Code:

[C#]
Workbook newbook = new Workbook();
newbook.Version = ExcelVersion.Version2010;
newbook.Worksheets.Clear();

Workbook tempbook = new Workbook();
string[] excelFiles = new String[] { "sample1.xlsx", "sample2.xlsx", "sample3.xlsx" };
for (int i = 0; i < excelFiles.Length; i++)
{
    tempbook.LoadFromFile(excelFiles[i]);
    foreach (Worksheet sheet in tempbook.Worksheets)
    {
        newbook.Worksheets.AddCopy(sheet);
    }
}

newbook.SaveToFile("result.xlsx", ExcelVersion.Version2010);
System.Diagnostics.Process.Start("result.xlsx");
[VB.NET]
Dim newbook As New Workbook()
newbook.Version = ExcelVersion.Version2010
newbook.Worksheets.Clear()

Dim tempbook As New Workbook()
Dim excelFiles As String() = New [String]() {"sample1.xlsx", "sample2.xlsx", "sample3.xlsx"}
For i As Integer = 0 To excelFiles.Length - 1
	tempbook.LoadFromFile(excelFiles(i))
	For Each sheet As Worksheet In tempbook.Worksheets
		newbook.Worksheets.AddCopy(sheet)
	Next
Next

newbook.SaveToFile("result.xlsx", ExcelVersion.Version2010)
System.Diagnostics.Process.Start("result.xlsx")
Monday, 19 March 2012 02:55

Easily Merge Excel Cells in C#, VB.NET

Excel cells merge is indispensable for handling Excel worksheet. When it comes to the problem of Excel cells merge, developers may encounter different solutions, the solution will be introduced is very simple since users can realize the task of excel cell merge by only one line of code by a .NET Excel component.

Spire.XLS for .NET allows developers to generate, read, write and manipulate Excel files without using MS Excel Automation. Using this .NET component, you can call the method: public void Spire.Xls. Worksheet. Range. Merge() to merge excel cells after loading an Excel file by invoking Workbook. LoadFromFile(string fileName, bool preserveMode) method.

Please preview the effect screenshot after merging the cells as below:

Merge Excel Cells

Here, you can download Spire.XLS for .NET, and follow the whole code below:

C# Merge Cells in Excel
using Spire.Xls;

namespace mergecells
{
    class Program
    {
        static void Main(string[] args)
        {
            //load an Excel file from system
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"..\mergecells.xls", ExcelVersion.Version97to2003);
       
            //merge Excel cells
            Worksheet sheet = workbook.Worksheets[0];
            //merge A3-C5 to one cell
            sheet.Range["A3:C5"].Merge();
            //merge B8-D10 to one cell
            sheet.Range["B8:D10"].Merge();
            //merge C13-E15 to one cell
            sheet.Range["C13:E15"].Merge();

            //save the workbook
            workbook.SaveToFile(@"cellsMerge.xls", ExcelVersion.Version97to2003);
        }
    }
}
VB.NET Merge Cells in Excel
Imports Spire.Xls

Namespace mergecells
	Class Program
		Private Shared Sub Main(args As String())
			'load an Excel file from system
			Dim workbook As New Workbook()
			workbook.LoadFromFile("..\mergecells.xls", ExcelVersion.Version97to2003)

			'merge Excel cells
			Dim sheet As Worksheet = workbook.Worksheets(0)
			'merge A3-C5 to one cell
			sheet.Range("A3:C5").Merge()
			'merge B8-D10 to one cell
			sheet.Range("B8:D10").Merge()
			'merge C13-E15 to one cell
			sheet.Range("C13:E15").Merge()

			'save the workbook
			workbook.SaveToFile("cellsMerge.xls", ExcelVersion.Version97to2003)
		End Sub
	End Class
End Namespace

Spire.XLS is a professional Excel component which enables developers/programmers to fast generate, read, write and modify Excel document for .NET and Silverlight. It supports C#, VB.NET, ASP.NET, ASP.NET MVC and Silverlight.

Thursday, 15 March 2012 09:31

How to Set Word Table Column Width

By using Spire.Doc, developers can create Word document with a table inside (Click to learn how to create table in Word document). But when users create table in Word document, they would not only create table with blank cells. They need set formats or sometimes set table size like column width. This article will show you how to set Word table column width.

Make sure Spire.Doc and Visual Studio are correctly installed on system. Follow the simple steps below to set Word table column width.

Step 1: Create a C# windows form application in Visual Studio. Add Spire.Doc.dll as reference. The default setting of Spire.Doc.dll is placed under "C:\Program Files\e-iceblue\Spire.Doc\Bin". Select assembly Spire.Doc.dll and click OK to add it to the project.

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

namespace TableWidth
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Fields
Imports Spire.Doc.Documents

Namespace TableWidth
	Public Partial Class Form1
		Inherits Form
		Public Sub New()
			InitializeComponent()
		End Sub
		Private Sub button1_Click(sender As Object, e As EventArgs)
		End Sub
	End Class
End Namespace

Step 2: Put the word document with table into the project folder. Use the following code to load it into project.

[C#]
Document doc = new Document();
            doc.LoadFromFile(@"..\..\Table.docx",FileFormat.Docx);
[VB.NET]
Dim doc As New Document()
doc.LoadFromFile("..\..\Table.docx", FileFormat.Docx)

Step 3: Because Spire.Doc doesn't have a direct method to set column width, we need set the first cell width of in each row.

[C#]
            for (int i = 0; i < document.Sections[0].Tables[0].Rows.Count; i++)
            {
                document.Sections[0].Tables[0].Rows[i].Cells[0].Width = 20;
            }
[VB.NET]
For i As Integer = 0 To document.Sections(0).Tables(0).Rows.Count - 1
	document.Sections(0).Tables(0).Rows(i).Cells(0).Width = 20
Next

Step 4: Save and Preview.

[C#]
document.SaveToFile(@"..\..\Sample.docx",FileFormat.Docx);
          
[VB.NET]
document.SaveToFile("..\..\Sample.docx", FileFormat.Docx)
System.Diagnostics.Process.Start("..\..\Test.pdf")

Now, the whole process is finished. Press F5 and click the button to run the project. The generated docx file can be found at the project debug folder. Check the effect.

Before Setting Width:

Word Table Column Width

After Setting Width:

Word Table Column Width

As a professional and powerful Word component, Spire.Doc doesn't need Microsoft Office Word Automation but also allows user to directly operate Word document, format and style and insert content to Word document.Click to learn more feature functions of Spire.Doc