Home > Articles > .Net Framework Articles > Simple solution to convert table in Word to Excel by Free API

Simple solution to convert table in Word to Excel by Free API

by sarker ishwar   on Nov 26, 2014   Category: .Net Framework  | Level: Beginner  |  Views: 1389    |  Points: 100   
Like this article? Bookmark and Share:
We often use Microsoft Excel for storing large amounts of data. If you also have the same situation with me that the data exists in Microsoft Word table document and then you want to use an Excel spreadsheet to manage it, my solution will be introduced here may be able to help you. In my solution, I use free DocX to parse Word document and free Spire.Xls API for creating Excel file. The below will introduce my solution in detail.

Application Overview

Firstly, I used DocX API to get table data from Word and then fill the data into a System.Data.DataTable object.

DocX document = DocX.Load("..\\..\\data.docx");

 

Step2: Get tables from document, here I only get the first table as an example.

//Get the first table of document

Table table = document.Tables[0];

 

Step3: Create a DataTable object and fill the data of Word table into it.

//Get the first table of document

Table table = document.Tables[0];

 

Step3: Create a DataTable object and fill the data of Word table into it.

//Create a DataTable object and named it as order

DataTable dt = new DataTable("order");

//Fill data of Word table into DataTable

DataColumn column;

for (int i = 0; i < table.ColumnCount; i++)

{

column = new DataColumn();

column.ColumnName = table.Rows[0].Cells[i].Paragraphs[0].Text;

dt.Columns.Add(column);

}

DataRow newRow;

for (int i = 1; i < table.RowCount; i++)

{

newRow = dt.NewRow();

Row row = table.Rows[i];

for (int j = 0; j < table.ColumnCount; j++)

{

newRow[j] = row.Cells[j].Paragraphs[0].Text;

}

dt.Rows.Add(newRow);


}

 

Effect screenshots as follows:

 

Original Word document:

DataTable:

Secondly, I use Spire.Xls API to create a Workbook object and insert dataTable into it, and then save to an .xlsx file.

Step1: Create an instance of Workbook and create an empty worksheet for it.

//Create an instance of Workbook.

Workbook workbook = new Workbook();

//Create an empty worksheet.

workbook.CreateEmptySheets(1);

//Get the first worksheet.

Worksheet sheet = workbook.Worksheets[0];

 

Step2: Import data from dataTable into worksheet.

//Insert data from datatable into Worksheet in the first row and first column.

sheet.InsertDataTable(dt, true, 1, 1);

 

Step3: Save to an excel file.

workbook.SaveToFile("Data.xlsx",ExcelVersion.Version2007);

 

Effect screenshot of generated Excel as below:




Like this article? Bookmark and Share:

Most viewed Articles

User Comments


No response found, be the first to review this article.

Submit feedback about this article

Please sign in to post feedback

Latest Posts