Hi,
I want to export the data from the selected rows of a datagridview to a table in a word document(i.e. docx file) to a new page every time I run the code using gembox.document. How can I do that?
Here is what I tried but getting an error System.InvalidCastException: Unable to cast object of type ‘System.Windows.Forms.DataGridViewTextBoxColumn’ to type ‘System.Data.DataColumn’.:
int rowCount = dataGridView1.SelectedRows.Count;
int columnCount = dataGridView1.Columns.Count;
var dataTable = new DataTable();
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
dataTable.Columns.Add(column.HeaderText);
}
foreach (DataGridViewRow row in dataGridView1.SelectedRows.OfType<DataGridViewRow>().OrderBy(x=>x.Index))
{
foreach (DataGridViewCell cell in row.Cells)
{
dataTable.Rows.Add(cell.Value.ToString());
}
}
// Create new document.
var document = new DocumentModel();
// Create Table element from DataTable object.
Table table = new Table(document, rowCount, columnCount,
(int r, int c) => new TableCell(document, new Paragraph(document, dataTable.Rows[r][c].ToString())));
// Insert first row as Table's header.
table.Rows.Insert(0, new TableRow(document, dataGridView1.Columns.Cast<DataColumn>().Select(
dataColumn => new TableCell(document, new Paragraph(document, dataColumn.ColumnName)))));
table.TableFormat.PreferredWidth = new TableWidth(100, TableWidthUnit.Percentage);
document.Sections.Add(new Section(document, table));
document.Save(@"D:\Proj\MyDoc\Insert DataTable.docx");
MessageBox.Show("Export complete");
The error is on the line of code table.Rows.Insert(0, new TableRow(document, dataGridView1.Columns.Cast<DataColumn>().Select( dataColumn => new TableCell(document, new Paragraph(document, dataColumn.ColumnName)))));
Further, how can I add a header to every new page of the document where I paste the table?
Help…