Click here to Skip to main content
15,895,864 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wanted to export datatagridviews to excel.
First, I want to read the first row of the first datagrid, export the first row. then after that, it will read the second datagrid. then export the data inside the datagrid2.
Then go to the next row of datagrid1 again. [REPEAT PROCESS]

But Only the gridview1 is showing on the excel file. What is wrong with the code?

VB
For i = 0 To DataGridView1.RowCount - 2
    //JUST A QUERY TO SHOW DATADATAGRIVIEW2   "select * from assettable where assetID = '" & DataGridView1.Rows(i).Cells(0).Value & "'"
    DataGridView2.DataSource = Me.bindingsource2
    DataGridView2.AutoGenerateColumns = True
    For j = 0 To DataGridView1.ColumnCount - 1
		'xlWorkSheet.Cells(i + 2, j + 1) = _
        'DataGridView1(j, i).Value.ToString()

        If j <= 14 Then
            xlWorkSheet.Cells(i + 2, j + 1) = _
                DataGridView1(j, i).Value.ToString()
        ElseIf j >= 14 Then
			xlWorkSheet.Cells(i + 2, j + 1) = _
				DataGridView1(j, i).Value.ToString()
			For y As Integer = 0 To DataGridView2.RowCount - 2
				For x As Integer = 0 To DataGridView2.ColumnCount - 1
					xlWorkSheet.Cells(y + j, x + j) = _
						DataGridView2(y, x).Value.ToString()
				Next
			Next
        End If
    Next
Next
Posted
Updated 21-Sep-14 19:10pm
v3

1 solution

Check this function
Exporting DataGridview To Excel - Some code suggestions[^]
Modify(also split) the above function like below
C#
public static void GridToString(DataGridView dgv, int iRowstobeExported)
{
// Change the code based on iRowstobeExported - For 1st Grid, only one & for 2nd Grid no limit. You should modify the logic based on iRowstobeExported
// for (int row = 0; row < dgv.RowCount - 1; row++)
// {
// }
}

I did split the fuction for you. After you done with above function, concatenate the outputStr strings & pass it to below function.
C#
public static void SaveAsCSV(string outputStr, string filename)
{
  byte[] output = Encoding.ASCII.GetBytes(outputStr);
  using (FileStream fs = new FileStream(filename, FileMode.Create))
  {
    using (BinaryWriter bw = new BinaryWriter(fs))
    {
      bw.Write(output, 0, output.Length);
      bw.Flush();
    }
  }
}

Now go ahead to customize(change the logic in 1st function)
 
Share this answer
 

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