Spire.Doc can help developers to create word table with data and format cells easily and it also supports to add text watermark into the word documents. This article will show you how to create a vertical table at one side of the word document, which looks like the vertical watermark in the word document.

Firstly, please check the effective screenshot of the vertical table at the right of the word document added by Spire.Doc:

How to create vertical table at one side of the word document

Here comes to the steps of how to create vertical table in C#.

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

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

Step 2: Add a table with rows and columns and set the text for the table.

Table table = section.AddTable();
table.ResetCells(1, 1);
TableCell cell = table.Rows[0].Cells[0];
table.Rows[0].Height = 150;
cell.AddParagraph().AppendText("Draft copy in vertical style");

Step 3: Set the TextDirection for the table to RightToLeftRotated.

cell.CellFormat.TextDirection = TextDirection.RightToLeftRotated;

Step 4: Set the table format.

table.TableFormat.WrapTextAround = true;
table.TableFormat.Positioning.VertRelationTo = VerticalRelation.Page;
table.TableFormat.Positioning.HorizRelationTo = HorizontalRelation.Page;
table.TableFormat.Positioning.HorizPosition = section.PageSetup.PageSize.Width- table.Width;
table.TableFormat.Positioning.VertPosition = 200;

Step 5: Save the document to file.

document.SaveToFile("result.docx",FileFormat.docx2013);

Full codes in C#:

using Spire.Doc;
using Spire.Doc.Documents;

namespace CreateVerticalTable
{
    class Program
    {
        static void Main(string[] args)
        {

            Document document = new Document();
            Section section=document.AddSection();
            Table table = section.AddTable();
            table.ResetCells(1, 1);
            TableCell cell = table.Rows[0].Cells[0];
            table.Rows[0].Height = 150;
            cell.AddParagraph().AppendText("Draft copy in vertical style");
            cell.CellFormat.TextDirection = TextDirection.RightToLeftRotated;
            table.Format.WrapTextAround = true;
            table.Format.Positioning.VertRelationTo = VerticalRelation.Page;
            table.Format.Positioning.HorizRelationTo = HorizontalRelation.Page;
            table.Format.Positioning.HorizPosition = section.PageSetup.PageSize.Width - table.Width;
            table.Format.Positioning.VertPosition = 200;

            document.SaveToFile(""result.docx"", FileFormat.Docx2013);

        }
    }
}
Tuesday, 04 November 2014 09:08

Insert an existing Table by cloning in C#

In some case, we need make some modifications in an existing table but don't want destroy the original data, so we would like to copy the existing table then make some changes in the new table. How could we get the copied table? The easiest method is clone. There would introduce a solution to copy table and modify some data then insert the new table after original table via Spire.Doc.

Spire.Doc for .NET, a stand-alone .NET Word component, provides a method, Table.clone() to allow users to copy an existing table.

The main steps of the solution:

Firstly: load the word document with a table.

Document doc = new Document();
doc.LoadFromFile(@"CopyTable.doc");

The original document effect screenshot:

Insert an existing Table by cloning

Secondly: extract the existing table and call the table.clone () method to copy it.

Section se = doc.Sections[0];
Table original_Table =(Table) se.Tables[0];
Table copied_Table = original_Table.Clone();

Thirdly: extract the last row then traversal its cells to modify data.

string[] st = new string[] { "Guyana", "Georgetown", "South America", "214969", "800000" };
//get the last row of copied table
TableRow lastRow = copied_Table.Rows[copied_Table.Rows.Count - 1];
//change lastRow data.
lastRow.Cells[i].CellFormat.Shading.BackgroundPatternColor = Color.Gray;
for (int i = 0; i < lastRow.Cells.Count; i++)
    {
    lastRow.Cells[i].Paragraphs[0].Text = st[i];       
     }

Finally: call Section. tables.add() method to add the copied table in section and save this document.

se.Tables.Add(copied_Table);
doc.SaveToFile("result.doc", FileFormat.Doc);
The result document effect screenshot:

Insert an existing Table by cloning

Full code:

using Spire.Doc;
using System.Drawing;

namespace InsertingaAnExistingTable
{
    class Program
    {
        static void Main(string[] args)
        { 
//load a word document
            Document doc = new Document();
            doc.LoadFromFile(@"CopyTable.doc");

// extract the existing table
            Section se = doc.Sections[0];
            Table original_Table =(Table) se.Tables[0];

// copy the existing table to copied_Table via Table.clone()
            Table copied_Table = original_Table.Clone();
string[] st = new string[] { "Guyana", "Georgetown", "South America", "214969", "800000" };
            //get the last row of table
            TableRow lastRow = copied_Table.Rows[copied_Table.Rows.Count - 1];
            //change last row data.
            lastRow.Cells[i].CellFormat.Shading.BackgroundPatternColor = Color.Gray;
            for (int i = 0; i < lastRow.Cells.Count; i++)
            {
                lastRow.Cells[i].Paragraphs[0].Text = st[i];
            }
// add copied_Table in section
            se.Tables.Add(copied_Table);
            doc.SaveToFile("result.doc", FileFormat.Doc);     
        }
    }
}

Content controls provide a way for you to design documents. When you add a content control to a document, the control is identified by a border, a title, and temporary text that can provide instructions to the user. According to Microsoft, content controls mainly benefit from two features:

  • Prevent users from editing or deleting protected sections of a document.
  • Bind parts of a document or template to data. You can bind content controls to database fields, managed objects in the .NET Framework, XML elements that are stored in the document, and other data sources.

Therefore, it is necessary for developers to get the properties of content controls when dealing content controls at run time. This article illustrates how to get all controls and their properties including alias, id and tag via Spire.Doc.

Firstly, check the test file that contains six content controls distributed in lines and a table. By default, the border and the title of the control do not appear if we don't click the protected section.

Test File:

Get alias, tag and id of content controls in a Word document in C#

Main Steps:

Step 1: Create a new Word document and load the test file.

Step 2: Create two lists to store tags which are distributed in lines and a table separately. Here, each content control will be identified by tag.

Step 3: Use foreach sentence to get all tags in the Word document.

Full Code:

static void Main(string[] args)
        {
            using (Document document = new Document(@"..\..\TestData\test.docx"))
            {
                StructureTags structureTags = GetAllTags(document);
                List<StructureDocumentTagInline> tagInlines = structureTags.tagInlines;

                string alias = tagInlines[0].SDTProperties.Alias;
                decimal id = tagInlines[0].SDTProperties.Id;
                string tag = tagInlines[0].SDTProperties.Tag;

                List<StructureDocumentTag> tags = structureTags.tags;
                alias = tags[0].SDTProperties.Alias;
                id = tags[0].SDTProperties.Id;
                tag = tags[0].SDTProperties.Tag;

            }
        }
       static StructureTags GetAllTags(Document document)
        {
            StructureTags structureTags = new StructureTags();
            foreach (Section section in document.Sections)
            {
                foreach (DocumentObject obj in section.Body.ChildObjects)
                {
                    if (obj.DocumentObjectType == DocumentObjectType.Paragraph)
                    {
                        foreach (DocumentObject pobj in (obj as Paragraph).ChildObjects)
                        {
                            if (pobj.DocumentObjectType == DocumentObjectType.StructureDocumentTagInline)
                            {
                                structureTags.tagInlines.Add(pobj as StructureDocumentTagInline);
                            }
                        }
                    }
                    else if (obj.DocumentObjectType == DocumentObjectType.Table)
                    {
                        foreach (TableRow row in (obj as Table).Rows)
                        {
                            foreach (TableCell cell in row.Cells)
                            {
                                foreach (DocumentObject cellChild in cell.ChildObjects)
                                {
                                    if (cellChild.DocumentObjectType == DocumentObjectType.StructureDocumentTag)
                                    {
                                        structureTags.tags.Add(cellChild as StructureDocumentTag);
                                    }
                                    else if (cellChild.DocumentObjectType == DocumentObjectType.Paragraph)
                                    {
                                        foreach (DocumentObject pobj in (cellChild as Paragraph).ChildObjects)
                                        {
                                            if (pobj.DocumentObjectType == DocumentObjectType.StructureDocumentTagInline)
                                            {
                                                structureTags.tagInlines.Add(pobj as StructureDocumentTagInline);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return structureTags;
        }
        public class StructureTags
           {
               List<StructureDocumentTagInline> m_tagInlines;
               public List<StructureDocumentTagInline> tagInlines
               {
                   get
                   {
                       if (m_tagInlines == null)
                           m_tagInlines = new List<StructureDocumentTagInline>();
                       return m_tagInlines;
                   }
                   set
                   {
                       m_tagInlines = value;
                   }
               }
               List<StructureDocumentTag> m_tags;
               public List<StructureDocumentTag> tags
               {
                   get
                   {
                       if (m_tags == null)
                           m_tags = new List<StructureDocumentTag>();
                       return m_tags;
                   }
                   set
                   {
                       m_tags = value;
                   }
               }
           }

Effect Screenshot:

Content controls in lines

Get alias, tag and id of content controls in a Word document in C#

Content controls in table

Get alias, tag and id of content controls in a Word document in C#

Tuesday, 09 September 2014 03:39

Marker Designer

Data

Name Capital Continent Area Population
Argentina Buenos Aires South America 2777815 32300003
Bolivia La Paz South America 1098575 7300000
Brazil Brasilia South America 8511196 150400000
Canada Ottawa North America 9976147 26500000
Chile Santiago South America 756943 13200000
Colombia Bagota South America 1138907 33000000
Cuba Havana North America 114524 10600000
Ecuador Quito South America 455502 10600000
El Salvador San Salvador North America 20865 5300000
Guyana Georgetown South America 214969 800000

Option

Excel Version:
downloads
  • Demo
  • Java
  • C# source
This demo shows you the usage of WorkbookDesigner.
import com.spire.data.table.DataTable;
import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class MarkerDesignerDemo {

    public void markerDesignerDemo(String filePath, String dataFilePath, String resultFilePath){
        Workbook data_book = new Workbook();
        data_book.loadFromFile(dataFilePath);
        DataTable table = data_book.getWorksheets().get(0).exportDataTable();

        Workbook workbook = new Workbook();
        workbook.loadFromFile(filePath);
        Worksheet sheet = workbook.getWorksheets().get(0);
        Worksheet sheet2 = workbook.getWorksheets().get(1);

        sheet.setName( "Result");
        sheet2.setName("DataSource");
        sheet2.insertDataTable(table,true,1,1);

        workbook.getMarkerDesigner().addParameter("Variable1", 1234.5678);
        workbook.getMarkerDesigner().addDataTable("Country", table);
        workbook.getMarkerDesigner().apply();

        sheet.getAllocatedRange().autoFitRows();
        sheet.getAllocatedRange().autoFitColumns();

        workbook.saveToFile(resultFilePath, FileFormat.Version2013);


    }
}
No Matter How Big or Small Your Project is,
Any technical question related to our product, contact us at support@e-iceblue.com.
Any question related to the purchase of product, contact us at sales@e-iceblue.com.
If you don't find the function you want, please request a free demo from us.
Tuesday, 09 September 2014 03:38

Calculate Formulas

Mathematic Functions:

Calculate symbol : Calculate Data:

Logic Function:

Calculate symbol : Calculate Data:

Simple Expression:

Calculate symbol : Calculate Data:

MID Functions:

Text : Start Number:
Number Charts:

Option:

Excel Version:
downloads
  • Demo
  • Java
  • C# source
This demo shows you how to calculate formulas and export data to datatable with calculating formulas.
import com.spire.xls.*;

public class CalculateFormulaDemo {
    public void CalculateFormulas(String resultFile){
        Workbook workbook = new Workbook();
        Worksheet sheet = workbook.getWorksheets().get(0);
        Calculate(workbook, sheet);
        workbook.saveToFile(resultFile, ExcelVersion.Version2010);
    }

    public void Calculate(Workbook workbook, Worksheet worksheet){
        int currentRow = 1;
        String currentFormula = null;
        Object formulaResult = null;
        String value = null;

        // Set width respectively of Column A ,Column B,Column C
        worksheet.setColumnWidth(1,32);
        worksheet.setColumnWidth(2,16);
        worksheet.setColumnWidth(3,16);

        //Set the value of Cell A1
        worksheet.getRange().get(currentRow++, 1).setValue("Examples of formulas :");

        // Set the value of Cell A2
        worksheet.getRange().get(++currentRow, 1).setValue("Test data:");

        // Set the style of Cell A1
        CellRange range = worksheet.getRange().get("A1");
        range.getStyle().getFont().isBold(true);
        range.getStyle().setFillPattern(ExcelPatternType.Solid);
        range.getStyle().setKnownColor(ExcelColors.LightGreen1);
        range.getStyle().getBorders().getByBordersLineType(BordersLineType.EdgeBottom).setLineStyle(LineStyleType.Medium);

        // Additive operation of mutiple cells

        worksheet.getRange().get(currentRow, 2).setNumberValue(7.3);
        worksheet.getRange().get(currentRow, 3).setNumberValue(5);
        worksheet.getRange().get(currentRow, 4).setNumberValue(8.2);
        worksheet.getRange().get(currentRow, 5).setNumberValue(4);
        worksheet.getRange().get(currentRow, 6).setNumberValue(3);
        worksheet.getRange().get(currentRow, 7).setNumberValue(11.3);

        // Create arithmetic expression string about cells
        currentFormula = "=Sheet1!$B$3 + Sheet1!$C$3+Sheet1!$D$3+Sheet1!$E$3+Sheet1!$F$3+Sheet1!$G$3";

        //Caculate arithmetic expression  about cells
        formulaResult = workbook.calculateFormulaValue(currentFormula);
        value = formulaResult.toString();
        worksheet.getRange().get(currentRow,2).setValue(value);

        // Set the value and format of two head cell
        worksheet.getRange().get(currentRow,1).setValue("Formulas");
        worksheet.getRange().get(currentRow,2).setValue("Results");
        worksheet.getRange().get(currentRow,2).setHorizontalAlignment(HorizontalAlignType.Right);
        range = worksheet.getRange().get(currentRow,1,currentRow,2);
        range.getStyle().getFont().isBold(true);
        range.getStyle().setKnownColor(ExcelColors.LightGreen1);
        range.getStyle().setFillPattern(ExcelPatternType.Solid);
        range.getStyle().getBorders().getByBordersLineType(BordersLineType.EdgeBottom).setLineStyle(LineStyleType.Medium);

        // Expression caculation
        // Create arithmetic tables enclosed type string
        currentFormula = "=33*3/4-2+10";
        worksheet.getRange().get(++currentRow,1).setText(currentFormula);

        // Caculate arithmetic expression
        formulaResult = workbook.calculateFormulaValue(currentFormula);

        value = formulaResult.toString();

        worksheet.getRange().get(currentRow,2).setValue(value);

        //Absolute value function
        // Create abosolute value function string
        currentFormula = "=ABS(-1.21)";
        worksheet.getRange().get(++currentRow,1).setText(currentFormula);

        // Caculate abosulte value function
        formulaResult = workbook.calculateFormulaValue(currentFormula);
        value = formulaResult.toString();
        worksheet.getRange().get(currentRow,2).setValue(value);

        // Sum function
        // Create sum function string
        currentFormula = "=SUM(18,29)";
        worksheet.getRange().get(++currentRow,1).setText(currentFormula);

        // Caculate sum function
        formulaResult = workbook.calculateFormulaValue(currentFormula);
        value = formulaResult.toString();
        worksheet.getRange().get(currentRow,2).setValue(value);

        //NOT function
        // Create NOT function string
        currentFormula = "=NOT(true)";
        worksheet.getRange().get(++currentRow,1).setText(currentFormula);

        //Caculate NOT function
        formulaResult = workbook.calculateFormulaValue(currentFormula);
        value = formulaResult.toString();
        worksheet.getRange().get(currentRow,2).setValue(value);
        worksheet.getRange().get(currentRow,2).setHorizontalAlignment(HorizontalAlignType.Right);

        //String Manipulation function
        //Get the substring
        // Build substring function
        currentFormula = "=MID(\"world\",4,2)";
        worksheet.getRange().get(++currentRow,1).setText(currentFormula);

        //Caculate substring function
        formulaResult = workbook.calculateFormulaValue(currentFormula);
        value = formulaResult.toString();
        worksheet.getRange().get(currentRow,2).setValue(value);

        worksheet.getRange().get(currentRow,2).setHorizontalAlignment(HorizontalAlignType.Right);

        // Random function

        // Create random function string.
        currentFormula = "=RAND()";
        worksheet.getRange().get(++currentRow,1).setText(currentFormula);

        //Caculate random function
        formulaResult = workbook.calculateFormulaValue(currentFormula);
        value = formulaResult.toString();
        worksheet.getRange().get(currentRow,2).setValue(value);


    }
}
No Matter How Big or Small Your Project is,
Any technical question related to our product, contact us at support@e-iceblue.com.
Any question related to the purchase of product, contact us at sales@e-iceblue.com.
If you don't find the function you want, please request a free demo from us.
Tuesday, 09 September 2014 03:33

Create Pivot Table

Tuesday, 09 September 2014 03:28

Charts

  • Demo
  • Java
  • C# source
This demo shows you how to create chart in an excel workbook.
import com.spire.xls.*;

public class ChartDemo {
    public void chartDemo(String excelFile, ExcelChartType chartType, String resultFileName){
        Workbook workbook = new Workbook();
		workbook.loadFromFile(excelFile);
        Worksheet worksheet = workbook.getWorksheets().get(0);
        
        setChart(worksheet,chartType);
        sheetStyle(workbook,worksheet);
        workbook.saveToFile(resultFileName+".xlsx",FileFormat.Version2013);

    }
    private void setChart(Worksheet sheet, ExcelChartType chartType){
        sheet.setName("Chart data");
        sheet.setGridLinesVisible(false);

        //Add a new  chart worsheet to workbook
        Chart chart = sheet.getCharts().add();
        chart.setChartType(chartType);

        //Set region of chart data
        chart.setDataRange(sheet.getCellRange("A1:C7"));
        chart.setSeriesDataFromRange(false);

        //Set position of chart
        chart.setLeftColumn(4);
        chart.setTopRow(2);
        chart.setRightColumn(12);
        chart.setBottomRow(22);

        //Chart title
        chart.setChartTitle("Sales market by country");
        chart.getChartTitleArea().isBold(true);
        chart.getChartTitleArea().setSize(12);

        chart.getPrimarySerieAxis().setTitle("Country");
        chart.getPrimarySerieAxis().getFont().isBold(true);
        chart.getPrimarySerieAxis().getTitleArea().isBold(true);

        chart.getPrimarySerieAxis().setTitle("Sales(in Dollars)");
        chart.getPrimarySerieAxis().hasMajorGridLines(false);
        chart.getPrimarySerieAxis().getTitleArea().setTextRotationAngle(90);
        chart.getPrimarySerieAxis().setMinValue(1000);
        chart.getPrimarySerieAxis().getTitleArea().isBold(true);

        chart.getPlotArea().getFill().setFillType(ShapeFillType.SolidColor);
        chart.getPlotArea().getFill().setForeKnownColor(ExcelColors.White);

        for (int i = 0; i < chart.getSeries().getCount(); i++){
            chart.getSeries().get(i).getFormat().getOptions().isVaryColor(true);
            chart.getSeries().get(i).getDataPoints().getDefaultDataPoint().getDataLabels().hasValue(true);
        }
        chart.getLegend().setPosition(LegendPositionType.Top);
    }

    public static void sheetStyle(Workbook workbook, Worksheet sheet){
        CellStyle oddStyle = workbook.getStyles().addStyle("oddStyle");
        oddStyle.getBorders().getByBordersLineType(BordersLineType.EdgeLeft).setLineStyle(LineStyleType.Thin);
        oddStyle.getBorders().getByBordersLineType(BordersLineType.EdgeTop).setLineStyle(LineStyleType.Thin);
        oddStyle.getBorders().getByBordersLineType(BordersLineType.EdgeBottom).setLineStyle(LineStyleType.Thin);
        oddStyle.setKnownColor(ExcelColors.LightGreen1);

        CellStyle evenStyle = workbook.getStyles().addStyle("evenStyle");
        evenStyle.getBorders().getByBordersLineType(BordersLineType.EdgeLeft).setLineStyle(LineStyleType.Thin);
        evenStyle.getBorders().getByBordersLineType(BordersLineType.EdgeRight).setLineStyle(LineStyleType.Thin);
        evenStyle.getBorders().getByBordersLineType(BordersLineType.EdgeTop).setLineStyle(LineStyleType.Thin);
        evenStyle.getBorders().getByBordersLineType(BordersLineType.EdgeBottom).setLineStyle(LineStyleType.Thin);
        evenStyle.setKnownColor(ExcelColors.LightTurquoise);

        for (int i = 0; i < sheet.getAllocatedRange().getRows().length; i++) {
            CellRange[] ranges = sheet.getAllocatedRange().getRows();
            if (ranges[i].getRow() != 0){
                if (ranges[i].getRow() % 2 == 0)
                {
                    ranges[i].setCellStyleName(evenStyle.getName());
                }
                else
                {
                    ranges[i].setCellStyleName(oddStyle.getName());
                }
            }
        }

        //Sets header style
        CellStyle styleHeader = workbook.getStyles().addStyle("headerStyle");
        styleHeader.getBorders().getByBordersLineType(BordersLineType.EdgeLeft).setLineStyle(LineStyleType.Thin);
        styleHeader.getBorders().getByBordersLineType(BordersLineType.EdgeRight).setLineStyle(LineStyleType.Thin);
        styleHeader.getBorders().getByBordersLineType(BordersLineType.EdgeTop).setLineStyle(LineStyleType.Thin);
        styleHeader.getBorders().getByBordersLineType(BordersLineType.EdgeBottom).setLineStyle(LineStyleType.Thin);
        styleHeader.setVerticalAlignment(VerticalAlignType.Center);
        styleHeader.setKnownColor(ExcelColors.Green);
        styleHeader.getFont().setKnownColor(ExcelColors.White);
        styleHeader.getFont().isBold(true);
        styleHeader.setHorizontalAlignment(HorizontalAlignType.Center);

        for (int i = 0; i < sheet.getRows()[0].getCount(); i++) {
            CellRange range = sheet.getRows()[0];
            range.setCellStyleName(styleHeader.getName());
        }

        sheet.getColumns()[sheet.getAllocatedRange().getLastColumn() -1].getStyle().setNumberFormat("\"$\"#,##0");
        sheet.getColumns()[sheet.getAllocatedRange().getLastColumn() -2].getStyle().setNumberFormat("\"$\"#,##0");
        sheet.getRows()[0].getStyle().setNumberFormat("General");

        sheet.getAllocatedRange().autoFitColumns();
        sheet.getAllocatedRange().autoFitRows();

        sheet.getRows()[0].setRowHeight(20);
    }
}

No Matter How Big or Small Your Project is,
Any technical question related to our product, contact us at support@e-iceblue.com.
Any question related to the purchase of product, contact us at sales@e-iceblue.com.
If you don't find the function you want, please request a free demo from us.
Tuesday, 09 September 2014 02:17

Conversion

Upload

Maximum file size: 1 MB. Files accepted: xls, xlsx, xlsb, ods.
Click here to browse files.
fileerrors

Convert to

Source file:
filename
Target file type:
  • Demo
  • Java
  • C# source
This demo shows you how to convert a Excel document (xls/xlsx/xlsb/ods) to PDF, HTML, Image.
import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;
import com.spire.xls.core.spreadsheet.HTMLOptions;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;


public class ConvertDemo {

   public void convertDemo(String filePath, String convertTo, String resultFileName) throws IOException {
       Workbook workbook = new Workbook();
       workbook.loadFromFile(filePath);
       ConvertFormat(workbook,convertTo,resultFileName);

   }
    private void ConvertFormat(Workbook workbook, String convertTo, String resultFileName) throws IOException {
        switch (convertTo){
            case "PDF":
                workbook.getConverterSetting().setSheetFitToPage(true);
                workbook.saveToFile(resultFileName + ".pdf", FileFormat.PDF);
                break;
            case "IMAGE":
                BufferedImage[] images = (BufferedImage[]) new Image[workbook.getWorksheets().size()];
                for (int i = 0; i < workbook.getWorksheets().size();i++){
                    images[i] = workbook.saveAsImage(i,300,300);
                }
                if (images != null && images.length > 0){
                    if (images.length == 1){
                        ImageIO.write(images[0],".PNG", new File(resultFileName+".png"));
                    }
                }else {
                    for (int j = 0; j < images.length;j++){
                        String fileName = String.format("image-{0}.png",j);
                        ImageIO.write(images[j],".PNG",new File(fileName));
                    }
                }
                    break;
            case "HTML":
                for (int i = 0; i < workbook.getWorksheets().size(); i++) {
                    HTMLOptions options = new HTMLOptions();
                    options.setImageEmbedded(true);
                    String htmlPath = String.format(resultFileName+"-{0}.html",i++);
                    workbook.getWorksheets().get(i).saveToHtml(htmlPath,options);
                }
                break;
            case "TIFF":
                workbook.saveToTiff(resultFileName+".tiff");
                break;
            case "XPS":
                workbook.saveToFile(resultFileName+".xps",FileFormat.XPS);
                break;
        }
    }
}
No Matter How Big or Small Your Project is,
Any technical question related to our product, contact us at support@e-iceblue.com.
Any question related to the purchase of product, contact us at sales@e-iceblue.com.
If you don't find the function you want, please request a free demo from us.
Thursday, 28 August 2014 06:12

Prevent Page Breaks in Word Tables in C#

All too often, we start a table near the bottom of a page. Microsoft Word automatically places a page break in a table if a single row or several rows are too long to fit between the top and bottom margins of the page. So we'd rather the same row can be placed on one page or have the entire table on the next page instead of being broken over two pages. In this article, I'll introduce you two ways to avoid page breaks in Word tables via Spire.Doc.

Assume that we have a Word table like this (Row 2 splits to different pages), we may want to optimize the layout by the following two methods.

Prevent Page Breaks in Word Tables

Method 1: Keep the entire table on the same page.

Step 1: Create a new Word document and load the test file.

Document doc = new Document("Test.docx");

Step 2: Get the table from Word document.

Table table = doc.Sections[0].Tables[0] as Table;

Step 3: Change the paragraph setting to keep them together.

           foreach (TableRow row in table.Rows)
            {
                foreach (TableCell cell in row.Cells)
                {
                  foreach (Paragraph p in cell.Paragraphs)
                   {
                       p.Format.KeepFollow = true;
                   }
                }
           }

Step 4: Save and launch the file.

      doc.SaveToFile("Result.docx", FileFormat.Docx2010);
      System.Diagnostics.Process.Start("Result.docx");

Output:

Prevent Page Breaks in Word Tables

Use this sentence to replace Step 3, you'll get the layout as below:

Prevent Page Breaks in Word Tables

Full C# Code:

Method 1

using Spire.Doc;
using Spire.Doc.Documents;
namespace PreventPageBreak
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document("Test.docx");
            Table table = doc.Sections[0].Tables[0] as Table;
            foreach (TableRow row in table.Rows)
            {
                foreach (TableCell cell in row.Cells)
                {
                    foreach (Paragraph p in cell.Paragraphs)
                    {
                        p.Format.KeepFollow = true;
                    }
                }
            }
            doc.SaveToFile("Result.docx", FileFormat.Docx2010);
            System.Diagnostics.Process.Start("Result.docx");
        }
    }
}
Monday, 30 June 2014 06:59

Remove Table from PowerPoint document

Spire.Presentation is a powerful and easy-to-use .NET component, especially designed for developers. Using Spire.Presentation you can generate, modify, convert, render, and print documents without installing Microsoft PowerPoint on your machine. There is a document in our website introducing you how to insert table. And in this document, I will introduce you how to remove tables within a PPT document.

Step 1: Create Presentation instance and load file.

Presentation presentation = new Presentation();
presentation.LoadFromFile("sample.ppt");

Step 2: Get the tables within the PPT document.

 List<IShape> shape_tems = new List<IShape>();
foreach (IShape shape in presentation.Slides[0].Shapes)
{
    if (shape is ITable)
    {
        //add new table to table list
        shape_tems.Add(shape);
    }
}

Step 3: Remove all tables.

foreach (IShape shape in shape_tems)
{
    presentation.Slides[0].Shapes.Remove(shape);
}

Step 4: Save the document.

presentation.SaveToFile("result.pptx", FileFormat.Pptx2010);

Download and install Spire.Presentation for .NET and refer to below code to remove tables within PPT document.

Screenshots:

Before:

Remove Table from PowerPoint document

After:

Remove Table from PowerPoint document

Full Code:

[C#]
//create Presentation instance and load file
Presentation presentation = new Presentation();
presentation.LoadFromFile("sample.ppt");

//get the tables in PowerPoint document
List<IShape> shape_tems = new List<IShape>();
foreach (IShape shape in presentation.Slides[0].Shapes)
{
    if (shape is ITable)
    {
        //add new table to table list
        shape_tems.Add(shape);
    }
}

//remove all tables
foreach (IShape shape in shape_tems)
{
    presentation.Slides[0].Shapes.Remove(shape);
}

//save the document
presentation.SaveToFile("result.pptx", FileFormat.Pptx2010);
System.Diagnostics.Process.Start("result.pptx");
[VB.NET]
'create Presentation instance and load file
Dim presentation As New Presentation()
presentation.LoadFromFile("sample.ppt")

'get the tables in PowerPoint document
Dim shape_tems As New List(Of IShape)()
For Each shape As IShape In presentation.Slides(0).Shapes
    If TypeOf shape Is ITable Then
        'add new table to table list
        shape_tems.Add(shape)
    End If
Next

'remove all tables
For Each shape As IShape In shape_tems
    presentation.Slides(0).Shapes.Remove(shape)
Next

'save the document
presentation.SaveToFile("result.pptx", FileFormat.Pptx2010)
System.Diagnostics.Process.Start("result.pptx")

If you couldn't successfully use Spire.Presentation, please refer Spire.Presentation Quick Start which can guide you quickly use Spire.Presentation.