Click here to Skip to main content
15,891,204 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I tried using clipboard
but it is exporting one grid only.
Please help me in exporting 2 or more grids in the single excel sheet.

What I have tried:

private void CopyGridToClipboard(DataGridView grid)
     {
         //Exclude row headers
         grid.RowHeadersVisible = false;

         //Include column headers
         grid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
         grid.SelectAll();
         DataObject dataObj = grid.GetClipboardContent();
         if (dataObj != null)
             Clipboard.SetDataObject(dataObj);

         //Set the visibility of row headers back
         grid.RowHeadersVisible = true;
     }

private void btnExport_Click(object sender, EventArgs e)
     {
         this.CopyGridToClipboard(dataGridView1);
       <code></code>
         //Open the excel application and add a workbook
         XL.Application application;
         XL.Workbook book;
         XL.Worksheet sheet;
         application = new XL.Application();
         application.Visible = true;
         book = application.Workbooks.Add();
         sheet = (XL.Worksheet)book.Worksheets[1];

         //label1 Text in Cell[1,1]
         ((XL.Range)sheet.Cells[1, 1]).Value = this.label1.Text;

         //textBox1 Text in Cell[1,2]
         ((XL.Range)sheet.Cells[1, 2]).Value = this.combSOName.SelectedValue.ToString();

         ((XL.Range)sheet.Cells[1, 4]).Value = this.label3.Text;

         //textBox1 Text in Cell[1,2]
         ((XL.Range)sheet.Cells[1, 5]).Value = this.comboPartno.Text;

         //Let row 3 empty
         //Paste grid into Cell[4,1]
         XL.Range gridRange = (XL.Range)sheet.Cells[6, 1];
         gridRange.Select();
         sheet.PasteSpecial(gridRange);


         this.CopyGridToClipboard(dataGridView2);
         XL.Range gridRange1 = (XL.Range)sheet.Cells[24, 1];
         gridRange.Select();

         sheet.PasteSpecial(gridRange1);




     }
Posted
Updated 19-Sep-17 21:09pm
v2
Comments
Richard MacCutchan 20-Sep-17 4:49am    
You need to use your debugger to gather more information. After each call to Clipboard.SetDataObject you should do a manual check to see what is on the clipboard.
Member 12305778 20-Sep-17 5:50am    
Yes
Thanks got in 2nd grid it should be gridrange1.select();
:)
Richard MacCutchan 20-Sep-17 6:27am    
Why not just use gridRange for both operations?
Member 12305778 26-Sep-17 4:35am    
Its gives same name multiple times.
Richard MacCutchan 26-Sep-17 4:40am    
No idea what that means. I suggest you edit your question and show your updated code.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900