Add Tables to your Word (doc) file
Create a .doc file (or a Word file, any version) and add a table with few columns and rows. You can add any number of tables in your doc file and import all the table data either in a single GridView control or in multiple GridView controls.
Add Office Interop Reference
Create a new Asp.Net project and add a reference of the "Microsoft-Office-Interop.Word" library to your project. The library provides a list of interfaces that you’ll need to get access to Ms-Word objects.
1) To add a reference, open the Solution Explorer window, right click your projects name, and choose Add Reference. There’s another way. From the "top" menu inside the .Net IDE, chick website and find and choose "Add Reference" option.
2) In the "Add Reference" window, choose the .Net tab and find Microsoft-Office-Interop.Word from the list of libraries. See the image.
I have added only one GridView control in my markup section. Since, I’ll be importing data from a single table from my doc file. You can add either multiple GridView controls in your markup section or you can create and add the controls dynamically using code behind procedure.
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="SiteMaster" %> <!DOCTYPE html> <html> <head> <title>Import data from Ms-Word to GridView</title> </head> <body> <form runat="server"> <div> <div style="font:15px Calibri; letter-spacing:1px;"> <!-- Add a FileUpload control and a button. --> <div style="padding:20px 0;"> Select a file: <asp:FileUpload ID="FileUpload" accept=".doc,.docx" runat="server" /> <input type="button" onserverclick="PopulateGrid" value="Populate Grid" runat="server" /> </div> <%--Add the GridView control.--%> <div> <asp:GridView ID="GridView1" CssClass="Grid" runat="server"></asp:GridView> <p><asp:Label id="lblConfirm" runat="server"></asp:Label></p> </div> </div> </div> </form> </body> </html>
using System; using System.Data; // FOR "DataTable". using Word = Microsoft.Office.Interop.Word; // For Ms-Word application. public partial class SiteMaster : System.Web.UI.MasterPage { protected void PopulateGrid(object sender, EventArgs e) { // ' Check if any file is selected. if ((FileUpload.HasFile)) { if (!Convert.IsDBNull(FileUpload.PostedFile) & FileUpload.PostedFile.ContentLength > 0) { // Save the file in the root folder. FileUpload.SaveAs(Server.MapPath(".") + "\\" + FileUpload.FileName); // Create Ms-Word objects. Word.Application objWord; objWord = new Word.Application(); Word.Document objDoc; try { // Open the Word file in "ReadOnly" mode. objDoc = objWord.Documents.Open(Server.MapPath(".") + @"\" + FileUpload.FileName, ReadOnly: true); if (objDoc.Tables.Count != 0) // Check if Word file has any tables. { if (objDoc.Tables[1].Columns.Count > 0) // Check if the table has columns. { int iTotalCols; // Get total columns in the table. iTotalCols = objDoc.Tables[1].Columns.Count; int iTotalRows; // Get total rows in the table. iTotalRows = objDoc.Tables[1].Rows.Count; int iRows, iCols; DataTable dt = new DataTable(); // Get the table columns and add it to the DataTable as "headers". for (iCols = 1; iCols <= iTotalCols; iCols++) dt.Columns.Add(objDoc.Tables[1].Cell(1, iCols).Range.Text); object[] myObj = new object[iTotalCols - 1 + 1]; // Now extract the table data. for (iRows = 2; iRows <= iTotalRows; iRows++) { var row = dt.NewRow(); // Create and add new row to the DataTable. for (iCols = 1; iCols <= iTotalCols; iCols++) myObj[iCols - 1] = objDoc.Tables[1].Cell(iRows, iCols).Range.Text; row.ItemArray = myObj; dt.Rows.Add(row); // Add a new row to the DataTable. } GridView1.DataSource = dt; // Finally, populate the grid with the data. GridView1.DataBind(); lblConfirm.Text = "Data successfully imported to GridView."; lblConfirm.Attributes.Add("style", "color:green"); } } } catch (Exception ex) { // Show a message (if any) on the web page. lblConfirm.Text = ex.Message; lblConfirm.Attributes.Add("style", "color:red"); } finally { // Clean up. objWord.Quit(); objWord = null; objDoc = null; } } } } }
I have a FileUpload control on my web page to select the .doc files. After checking the file properties, I am creating few Word objects like,
// Create Ms-Word objects.
Word.Application objWord;
objWord = new Word.Application();
Word.Document objDoc;
Next, I am opening the Word file in Read only mode. The file remains open in the background, until the entire process is over. I’ll close the open documents at the end or when I am done with the data extraction process.
With "objDoc" object, I am checking if there are any tables in the Word file and if the tables have columns (or values) in it.
objDoc.Tables[1].Columns.Count > 0
See the above line where I have mentioned the table index as [1]. That’s the first table. If you have multiple tables, you can run a loop and dynamically assign values as index.
I have then declared a DataTable class and created an object. A DataTable table creates an in-memory table (its temporary) with columns and rows that you can easily bind with a GridView control.
This DataTable will hold the data (in columns and rows) extracted from the Ms-Word table.
Option Explicit On Imports System.Data ' For "DataTable" Imports Word = Microsoft.Office.Interop.Word ' For Ms-Word application. Partial Class Site Inherits System.Web.UI.MasterPage Protected Sub PopulateGrid(sender As Object, e As EventArgs) If (FileUpload.HasFile) Then ' Check if any file is selected. If Not IsDBNull(FileUpload.PostedFile) And _ FileUpload.PostedFile.ContentLength > 0 Then ' Save the file in the root folder. FileUpload.SaveAs(Server.MapPath(".") & "\" & FileUpload.FileName) ' Create Ms-Word objects. Dim objWord As Word.Application objWord = New Word.Application Dim objDoc As Word.Document Try ' Open the Word file in "ReadOnly" mode. objDoc = objWord.Documents.Open(Server.MapPath(".") & "\" & FileUpload.FileName, [ReadOnly]:=True) If objDoc.Tables.Count <> 0 Then ' Check if Word file has any tables. If objDoc.Tables(1).Columns.Count > 0 Then ' Check if the table has columns. Dim iTotalCols As Integer ' Get total columns in the table. iTotalCols = objDoc.Tables(1).Columns.Count Dim iTotalRows As Integer ' Get total rows in the table. iTotalRows = objDoc.Tables(1).Rows.Count Dim iRows, iCols As Integer Dim dt As DataTable = New DataTable ' Get the table columns and add it to the DataTable as "headers". For iCols = 1 To iTotalCols dt.Columns.Add(objDoc.Tables(1).Cell(1, iCols).Range.Text) Next iCols Dim myObj As Object() = New Object(iTotalCols - 1) {} ' Now extract the table data. For iRows = 2 To iTotalRows Dim row = dt.NewRow() ' Create and add new row to the DataTable. For iCols = 1 To iTotalCols myObj(iCols - 1) = objDoc.Tables(1).Cell(iRows, iCols).Range.Text Next (iCols) row.ItemArray = myObj dt.Rows.Add(row) ' Add a new row to the DataTable. Next iRows GridView1.DataSource = dt ' Finally, populate the grid with the data. GridView1.DataBind() lblConfirm.Text = "Data successfully imported to GridView." lblConfirm.Attributes.Add("style", "color:green") End If End If Catch ex As Exception ' Show a message (if any) on the web page. lblConfirm.Text = ex.Message : lblConfirm.Attributes.Add("style", "color:red") Finally ' Clean up. objWord.Quit() : objWord = Nothing objDoc = Nothing End Try End If End If End Sub End Class
Simple, isn’t it.
Not just tables, you can import everything in a doc file to your Asp.Net application. The Office Interop objects simplify the process of data exchange between Office apps and .Net apps.
You’ll have to follow a very similar procedure if you want to import data from an Excel file to a GridView control in Asp.Net.
Once you have populated the data to the GridView, you can now numerous operations like a CRUD operations using the data in the grid.