Hi,
I'm trying to export the selected rows of a datagridview to a docx file with a specific header when I hit a button (a text and a date time picker which writes the current date):

Also note, every time I hit the button after selecting rows of the datagridview, the data(i.e. table) should be added to a new page of that same docx file with the same header format and not overwrite data.
I've done:
- void Export2docClick(object sender, EventArgs e)
- {
- //Table start.
- string html = "
";
";- //Adding HeaderRow.
- html += "
" + comboBox1.Text + " "; ";- foreach (DataGridViewColumn column in dataGridView1.Columns)
- {
- html += "
" + column.HeaderText + " ";- }
- html += "
- //Adding DataRow.
- foreach (DataGridViewRow row in dataGridView1.SelectedRows.OfType
().OrderBy(s=>s.Index)) - {
- html += "
"; ";- foreach (DataGridViewCell cell in row.Cells)
- {
- html += "
" + cell.Value.ToString() + " ";- }
- html += "
- }
- //Table end.
- html += "
- //Save the HTML string as HTML File.
- string htmlFilePath = @"F:\checking\DataGridView.htm";
- File.WriteAllText(htmlFilePath, html);
- //Convert the HTML File to Word document.
- _Application word = new Microsoft.Office.Interop.Word.Application();
- _Document wordDoc = word.Documents.Open(FileName: htmlFilePath, ReadOnly: false);
- foreach (Microsoft.Office.Interop.Word.Section section in wordDoc.Sections)
- {
- //Get the header range and add the header details.
- Microsoft.Office.Interop.Word.Range headerRange = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
- headerRange.Fields.Add(headerRange, WdFieldType.wdFieldPage);
- headerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
- headerRange.Font.ColorIndex = WdColorIndex.wdBlue;
- headerRange.Font.Size = 10;
- headerRange.Text = "Vizferma";
- }
- wordDoc.SaveAs(FileName: @"F:\checking\DataGridView.docx", FileFormat: WdSaveFormat.wdFormatXMLDocument);
- ((_Document)wordDoc).Close();
- ((_Application)word).Quit();
- //Delete the HTML File.
- File.Delete(htmlFilePath);
- MessageBox.Show("Done");
- }
How do I add the header part and also how do I make the code paste data in a new page instead of overwriting the file every time?
Furthermore, how do I sort the selected rows of the datagridview by say, column 2 values in ascending order?
Thanks in advance
Jayanta MukherjeePosted Apr 5, 2021, 12:52 PM
Rijwan AnsariPosted Apr 4, 2021, 5:44 PM
Rijwan AnsariPosted Apr 4, 2021, 5:41 PM