Manish Parmar

Manish Parmar

  • 1.5k
  • 113
  • 978

I want DataGridview details to be exported as Word file.

Jun 14 2020 8:01 AM
I am using Spire.Doc to export datagridview data to word, i am using below code, the problem is dont want to declare the array size it should be auto calculated as per the Rows of the Datagridview
 
Can anyone help me on the below where i can later add more than 1 Datagridview details also....
  1. using Spire.Doc;  
  2. using Spire.Doc.Documents;  
  3. using Spire.Doc.Fields;  
  4. Document doc = new Document();  
  5. Section section = doc.AddSection();  
  6. Spire.Doc.Table table3 = section.AddTable(true);  
  7. String[] Header3 = { "Column1""Column2" };  
  8. String[][] data3 = new String[4][];  
  9. for (int k = 0; k < 4; k++)  
  10. {  
  11. data3[k] = new string[this.DataGridView.ColumnCount];  
  12. for (int j = 0; j < this.DataGridView.ColumnCount; j++)  
  13. {  
  14. data3[k][j] = this.DataGridView.Rows[k].Cells[j].Value.ToString();  
  15. }  
  16. }  
  17. //Add Cells  
  18. table3.ResetCells(data3.Length + 1, Header3.Length);  
  19. table3.TableFormat.Borders.Horizontal.LineWidth = 1;  
  20. table3.TableFormat.Borders.Vertical.LineWidth = 1;  
  21. //Header Row  
  22. Spire.Doc.TableRow FRow3 = table3.Rows[0];  
  23. FRow3.IsHeader = true;  
  24. //Row Height  
  25. FRow3.Height = 23;  
  26. for (int i = 0; i < Header3.Length; i++)  
  27. {  
  28. //Cell Alignment  
  29. Paragraph p1 = FRow3.Cells[i].AddParagraph();  
  30. FRow3.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;  
  31. p1.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;  
  32. //Data Format  
  33. TextRange TR = p1.AppendText(Header3[i]);  
  34. TR.CharacterFormat.FontName = "Century Gothic";  
  35. TR.CharacterFormat.FontSize = 13;  
  36. //TR.CharacterFormat.TextColor = Color.Teal;  
  37. TR.CharacterFormat.Bold = true;  
  38. }  
  39. //Data Row  
  40. for (int r = 0; r < data3.Length; r++)  
  41. {  
  42. Spire.Doc.TableRow DataRow = table3.Rows[r + 1];  
  43. //Row Height  
  44. DataRow.Height = 20;  
  45. //C Represents Column.  
  46. for (int c = 0; c < data3[r].Length; c++)  
  47. {  
  48. //Cell Alignment  
  49. DataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;  
  50. //Fill Data in Rows  
  51. Paragraph p2 = DataRow.Cells[c].AddParagraph();  
  52. TextRange TR2 = p2.AppendText(data3[r][c]);  
  53. //Format Cells  
  54. p2.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;  
  55. TR2.CharacterFormat.FontName = "Century Gothic";  
  56. TR2.CharacterFormat.FontSize = 12;  
  57. //TR2.CharacterFormat.TextColor = Color.Brown;  
  58. }  
  59. }  
  60. doc.SaveToFile("OperateWord.docx", FileFormat.Docx);  
  61. System.Diagnostics.Process.Start("OperateWord.docx");  

Answers (2)