Knowledgebase (2300)
Word and Excel are two completely different file types. Word documents are used to write essays, letters or create reports, while Excel documents are used to save data in tabular form, make charts, or perform mathematical calculations. It is not recommended to convert a complex Word document to an Excel spreadsheet because Excel can hardly render content according to its original layout in Word.
However, if your Word document is primarily composed of tables and you want to analyze the table data in Excel, you can use Spire.Office for .NET to convert Word to Excel while maintaining good readability.
Install Spire.Office for .NET
To begin with, you need to add the DLL files included in the Spire.Office 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.Office
Convert Word to Excel in C# and VB.NET
This scenario actually uses two libraries in the Spire.Office package. They’re Spire.Doc for .NET and Spire.XLS for .NET. The former is used to read and extract content from a Word document, and the latter is used to create an Excel document and write data in the specific cells. To make this code example easy to understand, we created the following three custom methods that preform specific functions.
- ExportTableInExcel() - Export data from a Word table to specified Excel cells.
- CopyContentInTable() - Copy content from a table cell in Word to an Excel cell.
- CopyTextAndStyle() - Copy text with formatting from a Word paragraph to an Excel cell.
The following steps demonstrate how to export data from an entire Word document to a worksheet using Spire.Office for .NET.
- Create a Document object to load a Word file.
- Create a Worbbook object and add a worksheet named "WordToExcel" to it.
- Traverse though all the sections in the Word document, traverse through all the document objects under a certain section, and then determine if a document object is a paragraph or a table.
- If the document object is a paragraph, write the paragraph in a specified cell in Excel using CoypTextAndStyle() method.
- If the document object is a table, export the table data from Word to Excel cells using ExportTableInExcel() method.
- Auto fit the row height and column width in Excel so that the data within a cell will not exceed the bound of the cell.
- Save the workbook to an Excel file using Workbook.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Xls;
using System;
using System.Drawing;
namespace ConvertWordToExcel
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Load a Word file
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Invoice.docx");
//Create a Workbook object
Workbook wb = new Workbook();
//Remove the default worksheets
wb.Worksheets.Clear();
//Create a worksheet named "WordToExcel"
Worksheet worksheet = wb.CreateEmptySheet("WordToExcel");
int row = 1;
int column = 1;
//Loop through the sections in the Word document
foreach (Section section in doc.Sections)
{
//Loop through the document object under a certain section
foreach (DocumentObject documentObject in section.Body.ChildObjects)
{
//Determine if the object is a paragraph
if (documentObject is Paragraph)
{
CellRange cell = worksheet.Range[row, column];
Paragraph paragraph = documentObject as Paragraph;
//Copy paragraph from Word to a specific cell
CopyTextAndStyle(cell, paragraph);
row++;
}
//Determine if the object is a table
if (documentObject is Table)
{
Table table = documentObject as Table;
//Export table data from Word to Excel
int currentRow = ExportTableInExcel(worksheet, row, table);
row = currentRow;
}
}
}
//Auto fit row height and column width
worksheet.AllocatedRange.AutoFitRows();
worksheet.AllocatedRange.AutoFitColumns();
//Wrap text in cells
worksheet.AllocatedRange.IsWrapText = true;
//Save the workbook to an Excel file
wb.SaveToFile("WordToExcel.xlsx", ExcelVersion.Version2013);
}
//Export data from Word table to Excel cells
private static int ExportTableInExcel(Worksheet worksheet, int row, Table table)
{
CellRange cell;
int column;
foreach (TableRow tbRow in table.Rows)
{
column = 1;
foreach (TableCell tbCell in tbRow.Cells)
{
cell = worksheet.Range[row, column];
cell.BorderAround(LineStyleType.Thin, Color.Black);
CopyContentInTable(tbCell, cell);
column++;
}
row++;
}
return row;
}
//Copy content from a Word table cell to an Excel cell
private static void CopyContentInTable(TableCell tbCell, CellRange cell)
{
Paragraph newPara = new Paragraph(tbCell.Document);
for (int i = 0; i < tbCell.ChildObjects.Count; i++)
{
DocumentObject documentObject = tbCell.ChildObjects[i];
if (documentObject is Paragraph)
{
Paragraph paragraph = documentObject as Paragraph;
foreach (DocumentObject cObj in paragraph.ChildObjects)
{
newPara.ChildObjects.Add(cObj.Clone());
}
if (i < tbCell.ChildObjects.Count - 1)
{
newPara.AppendText("\n");
}
}
}
CopyTextAndStyle(cell, newPara);
}
//Copy text and style of a paragraph to a cell
private static void CopyTextAndStyle(CellRange cell, Paragraph paragraph)
{
RichText richText = cell.RichText;
richText.Text = paragraph.Text;
int startIndex = 0;
foreach (DocumentObject documentObject in paragraph.ChildObjects)
{
if (documentObject is TextRange)
{
TextRange textRange = documentObject as TextRange;
string fontName = textRange.CharacterFormat.FontName;
bool isBold = textRange.CharacterFormat.Bold;
Color textColor = textRange.CharacterFormat.TextColor;
float fontSize = textRange.CharacterFormat.FontSize;
string textRangeText = textRange.Text;
int strLength = textRangeText.Length;
ExcelFont font = cell.Worksheet.Workbook.CreateFont();
font.Color = textColor;
font.IsBold = isBold;
font.Size = fontSize;
font.FontName = fontName;
int endIndex = startIndex + strLength;
richText.SetFont(startIndex, endIndex, font);
startIndex += strLength;
}
if (documentObject is DocPicture)
{
DocPicture picture = documentObject as DocPicture;
cell.Worksheet.Pictures.Add(cell.Row, cell.Column, picture.Image);
cell.Worksheet.SetRowHeightInPixels(cell.Row, 1, picture.Image.Height);
}
}
switch (paragraph.Format.HorizontalAlignment)
{
case HorizontalAlignment.Left:
cell.Style.HorizontalAlignment = HorizontalAlignType.Left;
break;
case HorizontalAlignment.Center:
cell.Style.HorizontalAlignment = HorizontalAlignType.Center;
break;
case HorizontalAlignment.Right:
cell.Style.HorizontalAlignment = HorizontalAlignType.Right;
break;
}
}
}
}

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.
Sometimes, you may need to perform specific operations on multiple shapes in Excel, such as adding styles, resizing, or moving them around. Grouping shapes can help you accomplish this task more easily and efficiently. Once shapes are grouped, they are treated as a single entity and can be manipulated at the same time. In this article, you will learn how to programmatically group or ungroup shapes in Excel 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
Group Shapes in Excel using C# and VB.NET
To group certain shapes in an Excel worksheet, you need to use the Worksheet.GroupShapeCollection property to return a GroupShapeCollection object, and then call the GroupShapeCollection.Group() method. The following are the detailed steps:
- Initialize an instance of Workbook class.
- Get the first worksheet by its index through Workbook.Worksheets[int] property.
- Add several shapes to specific rows and columns in the worksheet using Worksheet.PrstGeomShapes.AddPrstGeomShape(int, int, int, int, PrstGeomShapeType) method.
- Get the group shape collection of the worksheet through Worksheet.GroupShapeCollection property.
- Group the shapes using GroupShapeCollection.Group(IShape[]) method.
- Save the result document using Workbook.SaveToFile(string) method.
- C#
- VB.NET
using Spire.Xls;
using Spire.Xls.Core;
using Spire.Xls.Core.MergeSpreadsheet.Collections;
using System.Drawing;
namespace GroupShapes
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
//Add four shapes
IPrstGeomShape shape1 = worksheet.PrstGeomShapes.AddPrstGeomShape(3, 3, 65, 50, PrstGeomShapeType.RoundRect);
shape1.Fill.FillType = ShapeFillType.SolidColor;
shape1.Fill.ForeColor = Color.Yellow;
shape1.Line.Weight = 0.1;
IPrstGeomShape shape2 = worksheet.PrstGeomShapes.AddPrstGeomShape(7, 3, 65, 50, PrstGeomShapeType.Ribbon);
shape2.Fill.FillType = ShapeFillType.SolidColor;
shape2.Fill.ForeColor = Color.Purple;
shape2.Line.Weight = 0.1;
IPrstGeomShape shape3 = worksheet.PrstGeomShapes.AddPrstGeomShape(3, 5, 65, 50, PrstGeomShapeType.Cloud);
shape3.Fill.FillType = ShapeFillType.SolidColor;
shape3.Fill.ForeColor = Color.LightGreen;
shape3.Line.Weight = 0.1;
IPrstGeomShape shape4 = worksheet.PrstGeomShapes.AddPrstGeomShape(7, 5, 65, 50, PrstGeomShapeType.Ellipse);
shape4.Fill.FillType = ShapeFillType.SolidColor;
shape4.Fill.ForeColor = Color.LightSkyBlue;
shape4.Line.Weight = 0.1;
//Group the shapes
GroupShapeCollection groupShapeCollection = worksheet.GroupShapeCollection;
groupShapeCollection.Group(new IShape[] { shape1, shape2, shape3, shape4});
//Save the result file
workbook.SaveToFile("GroupShapes.xlsx", ExcelVersion.Version2013);
}
}
}

Ungroup Shapes in Excel using C# and VB.NET
To ungroup the grouped shapes in an Excel worksheet, you can use the GroupShapeCollection. UnGroupAll() method. After the shapes are ungrouped, you can manipulate them individually. The following are the detailed steps:
- Initialize an instance of Workbook class.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet by its index through Workbook.Worksheets[int] property.
- Get the group shape collection of the worksheet through Worksheet.GroupShapeCollection property.
- Ungroup all the grouped shapes using GroupShapeCollection.UnGroupAll() method.
- Save the result document using Workbook.SaveToFile() method.
- C#
- VB.NET
using Spire.Xls;
using Spire.Xls.Core.MergeSpreadsheet.Collections;
namespace UngroupShapes
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
workbook.LoadFromFile("GroupShapes.xlsx");
//Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
//Ungroup the grouped shapes in the worksheet
GroupShapeCollection groupShapeCollection = worksheet.GroupShapeCollection;
groupShapeCollection.UnGroupAll();
//Save the result file
workbook.SaveToFile("UnGroupShapes.xlsx", ExcelVersion.Version2013);
}
}
}

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.
Picture files are among the most commonly used types of documents in people's lives. Sometimes, you may want to take all image files in a folder and convert them into slides for a PowerPoint presentation. Depending on your requirements, you can convert images to shapes or slide backgrounds. This article demonstrates how to convert images (in any common image format) to a PowerPoint document in Java using Spire.Presentation for Java.
- Convert Images to Backgrounds in PowerPoint in Java
- Convert Images to Shapes in PowerPoint in Java
- Convert Images to PowerPoint with Customized Slide Size in Java
Install Spire.Presentation for Java
First, you're required to add the Spire.Presentation.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.presentation</artifactId>
<version>10.11.4</version>
</dependency>
</dependencies>
Convert Images to Backgrounds in PowerPoint in Java
When images are converted as background of each slide in a PowerPoint document, they cannot be moved or scaled. The following are the steps to convert a set of images to a PowerPoint file as background images using Spire.Presentation for Java.
- Create a Presentation object.
- Set the slide size type to Sreen16x9.
- Get the image paths from a folder.
- Traverse through the images.
- Get a specific image and append it to the image collection of the document using Presentation.getImages().append() method.
- Add a slide to the document using Presentation.getSlides().append() method.
- Set the image as the background of the slide using the methods under SlideBackground object.
- Save the document to a PowerPoint file using Presentation.saveToFile() method.
- Java
import com.spire.presentation.*;
import com.spire.presentation.drawing.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
public class ConvertImagesAsBackground {
public static void main(String[] args) throws Exception {
//Create a Presentation object
Presentation presentation = new Presentation();
//Set slide size type
presentation.getSlideSize().setType(SlideSizeType.SCREEN_16_X_9);
//Remove the default slide
presentation.getSlides().removeAt(0);
//Get image files from a folder
File directoryPath = new File("C:\\Users\\Administrator\\Desktop\\Images");
File[] picFiles = directoryPath.listFiles();
//Loop through the images
for (int i = 0; i < picFiles.length; i++)
{
//Add a slide
ISlide slide = presentation.getSlides().append();
//Get a specific image
String imageFile = picFiles[i].getAbsolutePath();
//Append it to the image collection
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(imageFile));
IImageData imageData = presentation.getImages().append(bufferedImage);
//Set the image as the background image of the slide
slide.getSlideBackground().setType(BackgroundType.CUSTOM);
slide.getSlideBackground().getFill().setFillType(FillFormatType.PICTURE);
slide.getSlideBackground().getFill().getPictureFill().setFillType(PictureFillType.STRETCH);
slide.getSlideBackground().getFill().getPictureFill().getPicture().setEmbedImage(imageData);
}
//Save to file
presentation.saveToFile("output/ImagesToBackground.pptx", FileFormat.PPTX_2013);
}
}

Convert Images to Shapes in PowerPoint in Java
If you would like the images are moveable and resizable in the PowerPoint file, you can convert them as shapes. Below are the steps to convert images to shapes in a PowerPoint document using Spire.Presentation for Java.
- Create a Presentation object.
- Set the slide size type to Sreen16x9.
- Get the image paths from a folder.
- Traverse through the images.
- Get a specific image and append it to the image collection of the document using Presentation.getImages().append() method.
- Add a slide to the document using Presentation.getSlides().append() method.
- Add a shape with the size equal to the slide using ISlide.getShapes().appendShape() method.
- Fill the shape with the image using the methods under FillFormat object.
- Save the document to a PowerPoint file using Presentation.saveToFile() method.
- Java
import com.spire.presentation.*;
import com.spire.presentation.drawing.*;
import javax.imageio.ImageIO;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
public class ConvertImageToShape {
public static void main(String[] args) throws Exception {
//Create a Presentation object
Presentation presentation = new Presentation();
//Set slide size type
presentation.getSlideSize().setType(SlideSizeType.SCREEN_16_X_9);
//Remove the default slide
presentation.getSlides().removeAt(0);
//Get image files from a folder
File directoryPath = new File("C:\\Users\\Administrator\\Desktop\\Images");
File[] picFiles = directoryPath.listFiles();
//Loop through the images
for (int i = 0; i < picFiles.length; i++)
{
//Add a slide
ISlide slide = presentation.getSlides().append();
//Get a specific image
String imageFile = picFiles[i].getAbsolutePath();
//Append it to the image collection
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(imageFile));
IImageData imageData = presentation.getImages().append(bufferedImage);
//Add a shape with the size equal to the slide
IAutoShape shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle2D.Float(0, 0, (float) presentation.getSlideSize().getSize().getWidth(), (float)presentation.getSlideSize().getSize().getHeight()));
//Fill the shape with image
shape.getLine().setFillType(FillFormatType.NONE);
shape.getFill().setFillType(FillFormatType.PICTURE);
shape.getFill().getPictureFill().setFillType(PictureFillType.STRETCH);
shape.getFill().getPictureFill().getPicture().setEmbedImage(imageData);
}
//Save to file
presentation.saveToFile("output/ImagesToShape.pptx", FileFormat.PPTX_2013);
}
}

Convert Images to PowerPoint with Customized Slide Size in Java
If the aspect ratio of your images is not 16:9, or they are not in a standard slide size, you can create slides based on the actual size of the pictures. This will prevent the image from being over stretched or compressed. The following are the steps to convert images to a PowerPoint document with customized slide size using Spire.Presentation for Java.
- Create a Presentation object.
- Create a PdfUnitConvertor object, which is used to convert pixel to point.
- Get the image paths from a folder.
- Traverse through the images.
- Get a specific image and append it to the image collection of the document using Presentation.getImages().append() method.
- Get the image width and height, and convert them to point.
- Set the slide size of the presentation based on the image size using Presentation.getSlideSize().setSize() method.
- Add a slide to the document using Presentation.getSlides().append() method.
- Set the image as the background image of the slide using the methods under SlideBackground object.
- Save the document to a PowerPoint file using Presentation.saveToFile() method.
- Java
import com.spire.pdf.graphics.PdfGraphicsUnit;
import com.spire.pdf.graphics.PdfUnitConvertor;
import com.spire.presentation.*;
import com.spire.presentation.drawing.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
public class CustomizeSlideSize {
public static void main(String[] args) throws Exception {
//Create a Presentation object
Presentation presentation = new Presentation();
//Remove the default slide
presentation.getSlides().removeAt(0);
//Get image files from a folder
File directoryPath = new File("C:\\Users\\Administrator\\Desktop\\Images");
File[] picFiles = directoryPath.listFiles();
//Create a PdfUnitConvertor object
PdfUnitConvertor convertor = new PdfUnitConvertor();
//Loop through the images
for (int i = 0; i < picFiles.length; i++)
{
//Get a specific image
String imageFile = picFiles[i].getAbsolutePath();
//Append it to the image collection
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(imageFile));
IImageData imageData = presentation.getImages().append(bufferedImage);
//Get image height and width in pixel
int height = imageData.getHeight();
int width = imageData.getWidth();
//Convert pixel to point
float widthPoint = convertor.convertUnits(width, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point);
float heightPoint= convertor.convertUnits(height, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point);
//Set slide size
presentation.getSlideSize().setSize(new Dimension((int)widthPoint, (int)heightPoint));
//Add a slide
ISlide slide = presentation.getSlides().append();
//Set the image as the background image of the slide
slide.getSlideBackground().setType(BackgroundType.CUSTOM);
slide.getSlideBackground().getFill().setFillType(FillFormatType.PICTURE);
slide.getSlideBackground().getFill().getPictureFill().setFillType(PictureFillType.STRETCH);
slide.getSlideBackground().getFill().getPictureFill().getPicture().setEmbedImage(imageData);
}
//Save to file
presentation.saveToFile("output/CustomizeSlideSize.pptx", FileFormat.PPTX_2013);
}
}

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.