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)
- {
-
- string html = "<table cellpadding='5' cellspacing='0' style='border: 1px solid #ccc;font-size: 9pt;font-family:arial'>";
-
-
- html += "<tr><th colspan=3 style='background-color: #B8DBFD;border: 1px solid #ccc'>" + comboBox1.Text + "</th><tr>";
- foreach (DataGridViewColumn column in dataGridView1.Columns)
- {
- html += "<th style='background-color: #B8DBFD;border: 1px solid #ccc'>" + column.HeaderText + "</th>";
- }
- html += "</tr>";
-
-
- foreach (DataGridViewRow row in dataGridView1.SelectedRows.OfType<DataGridViewRow>().OrderBy(s=>s.Index))
- {
- html += "<tr>";
- foreach (DataGridViewCell cell in row.Cells)
- {
- html += "<td style='width:180px;border: 1px solid #ccc'>" + cell.Value.ToString() + "</td>";
- }
- html += "</tr>";
- }
-
-
- html += "</table>";
-
-
- string htmlFilePath = @"F:\checking\DataGridView.htm";
- File.WriteAllText(htmlFilePath, html);
-
-
- _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)
- {
-
- 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();
-
-
- 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