向下移动单元格,因为数据已在Excel中重写

时间:2016-08-04 08:23:54

标签: vb.net excel datagridview

下午好。

我有一个Excel文件,这就是它的外观。

enter image description here

我有一个看起来像这样的VB.Net程序。

enter image description here

现在点击Print Transmittal Form后,Datagridview中的数据将转换为我创建的Excel格式,但是有些错误,这里是输出。

enter image description here

数据会覆盖此部分。

enter image description here

我该怎样防止这种情况?而不是写单元格,被覆盖的部分将根据datagridview上的数据向下移动。

这是我的代码。

   If DataGridView1.Rows.Count = 0 Then
            MsgBox("Nothing to Export")
        Else
            Dim ExcelApp As Object, ExcelBook As Object
            Dim ExcelSheet As Object
            Dim rowIndex As Integer = 1
            Dim total As Double = 0

            ExcelApp = CreateObject("Excel.Application")
            ExcelBook = ExcelApp.Workbooks.Open("c:\SR Transmittal.xlsx")
            ExcelSheet = ExcelBook.WorkSheets("Transmittal Form")
            rowIndex += 11
            With ExcelSheet
                For i As Integer = 0 To DataGridView1.Rows.Count - 1
                    Dim columnIndex As Integer = 0
                    Do Until columnIndex
                        ExcelSheet.Cells(i + 12, columnIndex + 2).Value = DataGridView1.Item("ItemCode", i).Value.ToString
                        ExcelSheet.Cells(i + 12, columnIndex + 3).Value = DataGridView1.Item("Description", i).Value.ToString
                        ExcelSheet.Cells(i + 12, columnIndex + 4).Value = DataGridView1.Item("RequestedQty", i).Value.ToString
                        ExcelSheet.Cells(i + 12, columnIndex + 5).Value = DataGridView1.Item("UOM", i).Value.ToString
                        ExcelSheet.Cells(i + 12, columnIndex + 6).Value = DataGridView1.Item("UnitPrice", i).Value.ToString
                        ExcelSheet.Cells(i + 12, columnIndex + 7).Value = DataGridView1.Item("Total", i).Value.ToString
                        ExcelSheet.Cells(i + 12, columnIndex + 8).Value = DataGridView1.Item("Remarks", i).Value.ToString
                        .cells(i + 12, columnIndex + 4).NumberFormat = "#,##0.00"
                        .cells(i + 12, columnIndex + 6).NumberFormat = "#,##0.00"
                        .cells(i + 12, columnIndex + 7).NumberFormat = "#,##0.00"
                        columnIndex += rowIndex
                        .Columns("A:Z").EntireColumn.AutoFit()
                        .Columns("A:Z").EntireColumn.Font.Size = 9
                    Loop

                Next

            End With
            ExcelApp.Visible = True
            ExcelSheet = Nothing
            ExcelBook = Nothing
            ExcelApp = Nothing
        End If

TYSM寻求帮助

1 个答案:

答案 0 :(得分:0)

最近在类似的东西上工作,我通过在插入数据之前插入一个新行来实现它。对你而言,它看起来像是:

For i As Integer = 0 To DataGridView1.Rows.Count - 1
    oSheet.Range(oSheet.Cells(i + 12, 2), oSheet.Cells(i + 12, 8)).Insert(Shift:=Excel.XlDirection.xlDown)
    '... add row data

另外,FWIW使用columnIndex及其Do Until完全冗余?循环只会运行一次(在添加12(rowIndex)之前?