问题描述
我想将datatagridviews导出为excel。
首先,我想读取第一个数据网格的第一行,导出第一行。然后,它将读取第二个数据网格。然后导出datagrid2中的数据。
然后再次转到datagrid1的下一行。 [REPEAT PROCESS]
但只有gridview1显示在excel文件中。代码有什么问题?
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?
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
推荐答案
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++)
// {
// }
}
我为你分开了功能。完成上述功能后,连接 outputStr
字符串&将它传递给下面的函数。
I did split the fuction for you. After you done with above function, concatenate the outputStr
strings & pass it to below function.
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();
}
}
}
现在继续自定义(更改第1个函数中的逻辑)
Now go ahead to customize(change the logic in 1st function)
这篇关于导出到Excel:两个DataGridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!