Reputation: 47
I'm trying to loop over the datatable and create word table. So far if I have 3 rows in the datatable they are being inserted into the first row of my Microsoft Word table, instead I want every row from the datatable into a new row in Microsoft Word table. Below is my code :
protected void Button2_Click(object sender, EventArgs e)
{
PullData();
gvd2.DataSource = dataTable;
gvd2.DataBind();
// Create a document.
using (DocX document = DocX.Create(@"D:\Test.docx"))
{
// Add a Table to this document.
Novacode.Table t = document.AddTable(2, 3);
// Specify some properties for this Table.
t.Alignment = Alignment.center;
t.Design = TableDesign.MediumGrid1Accent2;
// Add content to this Table.
t.Rows[0].Cells[0].Paragraphs.First().Append("A");
//foreach (DataRow row in dataTable.Rows)
//{
// t.Rows[1].Cells[0].Paragraphs.First().Append(row["IssueSubjectType"].ToString());
//}
// Loop through the rows in the Table and insert data from the data source.
for (int row = 1; row < t.RowCount; row++)
{
for (int cell = 0; cell < t.Rows[row].Cells.Count; cell++)
{
Paragraph cell_paragraph =t.Rows[row].Cells[cell].Paragraphs[0];
cell_paragraph.InsertText(dataTable.Rows[row - 1].ItemArray[cell].ToString(), false);
}
}
// Insert the Table into the document.
document.InsertTable(t);
// Save the Document.
document.Save();
// Release this document from memory.
document.Dispose();
}
}
private DataTable dataTable = new DataTable();
// method to pull data from database to datatable
public void PullData()
{
using (SqlConnection sqlConn = new SqlConnection("Data Source=.;Initial Catalog=UAE_OG-Interanl;Integrated Security=True"))
{
string sqlQuery = @"SELECT IssueSubjectType from tbl_IssueStoPublicate WHERE IssueNumber = '625' order by IssueSubjectOrder desc";
using (SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn))
{
SqlDataAdapter ds = new SqlDataAdapter(cmd);
ds.Fill(dataTable);
}
}
}
Any help would be a lifesaver.
Upvotes: 1
Views: 1641
Reputation: 1
https://github.com/xceedsoftware/DocX/blob/master/Examples/Samples/Table/TableSample.cs
int size = 3;
DocX docX = DocX.Create(result, DocumentTypes.Document);
Table table = docX.AddTable(size, size);
table.AutoFit = AutoFit.Contents;
for (int i = 0; i <= (int)TableBorderType.InsideV; i++)
table.SetBorder((TableBorderType)i, new Border());
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
table.Rows[i].Cells[j].Paragraphs[0].InsertText(i + " | " + j);
docX.InsertParagraph().InsertTableBeforeSelf(table);
docX.Save();
Upvotes: 0