2016-08-31 3 views
0

Я хочу экспортировать свои строки datagridview в существующий шаблон excel с заголовками, которые начнутся с ячейки A10: AA10.vb.net Экспорт Datagridview в excel template

Это шаблон:

enter image description here

Я попробовал этот

Public Sub exportToexcel() 


    Dim default_location As String = "D:\Book1.xlsx" 

    Dim dset As New DataSet 

    dset.Tables.Add() 

    For i As Integer = 0 To dgvReports.ColumnCount - 1 
     dset.Tables(0).Columns.Add(dgvReports.Columns(i).HeaderText) 
    Next 
    add rows to the table 
    Dim dr1 As DataRow 
    For i As Integer = 0 To dgvReports.RowCount - 1 
     dr1 = dset.Tables(0).NewRow 
     For j As Integer = 0 To dgvReports.Columns.Count - 1 

      dr1(j) = dgvReports.Rows(i).Cells(j).Value 


     Next 
     dset.Tables(0).Rows.Add(dr1) 
    Next 

    Dim excel As Microsoft.Office.Interop.Excel.Application 
    excel = New Microsoft.Office.Interop.Excel.Application 
    Dim wBook As Microsoft.Office.Interop.Excel.Workbook 
    Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet 

    excel.Visible = True 
    excel.UserControl = True 

    wBook = excel.Workbooks.Add(System.Reflection.Missing.Value) 
    wSheet = wBook.Sheets("Sheet1") 
    excel.Range("A50:I50").EntireColumn.AutoFit() 
    With wBook 
     .Sheets("Sheet1").Select() 
     .Sheets(1).Name = "Sheet1" 

    End With 

    Dim dt As System.Data.DataTable = dset.Tables(0) 
    ' wSheet.Cells(1).value = strFileName 
    For Each col As DataGridViewColumn In dgvReports.Columns 
     wSheet.Cells(1, col.Index + 1) = col.HeaderText.ToString 
    Next 


    For i = 0 To dgvReports.RowCount - 1 
     For j = 0 To dgvReports.ColumnCount - 1 
      wSheet.Columns.NumberFormat = "@" 
      wSheet.Cells(i + 2, j + 1).value = dgvReports.Rows(i).Cells(j).Value.ToString 
     Next j 
    Next i 

    wSheet.Columns.AutoFit() 


    Dim blnFileOpen As Boolean = False 
    Try 
     Dim fileTemp As System.IO.FileStream = System.IO.File.OpenWrite(default_location) 
     fileTemp.Close() 
    Catch ex As Exception 
     blnFileOpen = False 
    End Try 

    If System.IO.File.Exists(default_location) Then 
     System.IO.File.Delete(default_location) 
    End If 
    wBook.SaveAs(default_location) 
    excel.Workbooks.Open(default_location) 
    excel.Visible = True 
End Sub 

This только создает новый Excel файл. Мне просто нужно почувствовать существующий файл excel.

+0

Что с downvote? :/ – Redentoru

+0

Не уменьшалось, но я думаю, потому что у вашего «вопроса» не возникает вопрос ... Так в чем проблема? – Esko

ответ

0

Заменить строку:

wBook = excel.Workbooks.Add(System.Reflection.Missing.Value) 

этот код добавит новую книгу вашего нов созданный Excel.

Это будет открыт файл назначен default_location переменной:

wBook = excel.Workbooks.Open(default_location) 
Смежные вопросы