Reputation: 115
I need to export Dataset Tables to Word. I have tried a solution using Interop Word. Here I'm facing a problem,
I need to Place the tables in the word document with a series of space, my problem I cant able to create a new table each table on the Dataset.
Here is my code,
private void Exporttoword_Click(object sender, EventArgs e)
{
try
{
DataSet Ds = objMB.ExeQueryStrRetDsBL("SP_PreviewSeries" + cbMatches.SelectedValue, 1);
object oMissing = System.Reflection.Missing.Value;
object oEndOfDoc = "\\endofdoc";
Microsoft.Office.Interop.Word._Application objWord;
Microsoft.Office.Interop.Word._Document objDoc;
objWord = new Microsoft.Office.Interop.Word.Application();
objWord.Visible = true;
objDoc = objWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
for (var w = 0; w < Ds.Tables.Count; w++)
{
Microsoft.Office.Interop.Word.Table objTable;
Microsoft.Office.Interop.Word.Range wrdRng = objDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
objTable = objDoc.Tables.Add(wrdRng, Convert.ToInt32(Ds.Tables[w].Rows.Count), Convert.ToInt32(Ds.Tables[w].Columns.Count), ref oMissing, ref oMissing);
objTable.Range.ParagraphFormat.SpaceAfter = 3;
for (var i = 0; i < Ds.Tables[w].Rows.Count; i++)
for (var j = 0; j < Ds.Tables[w].Columns.Count; j++)
{
objTable.Cell(i + 1, j + 1).Range.Text = Ds.Tables[w].Rows[i][j].ToString();
objTable.Cell(i + 1, j + 1).Range.Borders.Enable = 1;
}
objTable.Rows[1].Range.Font.Bold = 1;
objTable.Rows[1].Range.Font.Italic = 1;
}
this.Close();
string fp = @"D:\Practice\test.docx";
objDoc.SaveAs2(fp);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Upvotes: 3
Views: 1892
Reputation: 101
You need to declare a Paragraph like Word inside your for loop.
Microsoft.Office.Interop.Word.Paragraph paragraph;
and at the end of for loop
paragraph = objDoc.Paragraphs.Add();
This solution works fine for me. Try this.
Upvotes: 1