Hi Smile,
Please refer below sample.
SQL
CREATE TABLE [Questions]
(
[QuestionId] INT IDENTITY(1,1),
[Question] VARCHAR(200) NULL,
[Option1] VARCHAR(50) NULL,
[Option2] VARCHAR(50) NULL,
[Option3] VARCHAR(50) NULL,
[Option4] VARCHAR(50) NULL
)
HTML
<asp:Button Text="Import" ID="btnImport" runat="server" OnClick="Import" />
<hr />
<asp:GridView ID="gvQuestions" AutoGenerateColumns="true" runat="server">
</asp:GridView>
Namespaces
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using Microsoft.Office.Interop.Word;
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports Microsoft.Office.Interop.Word
Code
C#
protected void Import(object sender, EventArgs e)
{
string filePath = Server.MapPath("~/Files/Questions1_Table.docx");
Application word = new Application();
Document doc = new Document();
object missing = System.Type.Missing;
object fileName = filePath;
Microsoft.Office.Interop.Word.Table table = null;
doc = word.Documents.Open(ref fileName,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);
for (int i = 0; i < doc.Tables.Count; i++)
{
table = doc.Tables[i + 1];
}
gvQuestions.DataSource = GetDataTableFromWordTable(table);
gvQuestions.DataBind();
doc.Close(ref missing, ref missing, ref missing);
((_Application)word).Quit();
}
private System.Data.DataTable GetDataTableFromWordTable(Microsoft.Office.Interop.Word.Table table)
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.AddRange(new DataColumn[] {
new DataColumn("Question"),
new DataColumn("Option1"),
new DataColumn("Option2"),
new DataColumn("Option3"),
new DataColumn("Option4")
});
string question = string.Empty;
for (int i = 1; i < table.Rows.Count; i++)
{
Row row = table.Rows[i];
if (row.Cells.Count == 2)
{
question = row.Cells[1].Range.Text;
}
if (row.Cells.Count == 4)
{
string option1 = row.Cells[1].Range.Text;
string option2 = row.Cells[3].Range.Text;
row = table.Rows[i + 1];
string option3 = row.Cells[1].Range.Text;
string option4 = row.Cells[3].Range.Text;
i++;
dt.Rows.Add(question, option1, option2, option3, option4);
string query = "INSERT INTO Question VALUES(@Question, @Opton1, @Opton2, @Opton3, @Opton4)";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Parameters.AddWithValue("@Name", question);
cmd.Parameters.AddWithValue("@Opton1", option1);
cmd.Parameters.AddWithValue("@Opton2", option2);
cmd.Parameters.AddWithValue("@Opton3", option3);
cmd.Parameters.AddWithValue("@Opton4", option4);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
question = string.Empty;
}
}
return dt;
}
Screenshots
MS Word
Output