2013-09-04 1 views
0

DataGrid controldata se으로 채워집니다.DataGrid export to exc

DataGrid 컨트롤에서 설정된 모든 데이터 필드를 표시하지 않습니다.

DataGrid에서 excel file을 만들고 싶습니다.

솔루션을 얻는 방법?

(창 양식, vb net 1.1) 어쩌면이 프린 일에

+0

DataGrid에서 Excel을 내보내시겠습니까? – Sathish

답변

0

.

String path = @"D:\users\...."; 
    //your path 


String connStr = "Provider=//your provider;Data Source=" + path + ";Extended Properties=Excel 12.0;"; 

      //The connection to that file 

      OleDbConnection conn = new OleDbConnection(connStr); 

      //The query 

      string strSQL = "SELECT * FROM [?]"; 

      //The command 

      OleDbCommand cmd = new OleDbCommand(/*The query*/strSQL, /*The connection*/conn); 

      DataTable dT = new DataTable(); 

      conn.Open(); 

      try 

      { 

       OleDbDataReader dR = cmd.ExecuteReader(); 

       dT.Load(dR); 

       bS.DataSource = dT; 

       dGV.DataSource = bS; 

      } 

      catch (Exception ex) 

      { 

       MessageBox.Show(ex.Message); 

      } 

      finally 

      { 

       conn.Close(); 

      } 
+0

이것은 무엇입니까 ?? 그것은 수출 방법이 아닙니다 : ( –

+0

쉬운 방법 : http://zamov.online.fr/EXHTML/CSharp/CSharp4.html 캐치 앤 시도없이. –

+0

어쨌든 덕분에 Nejc Galof –

1

Link

또는

Imports Excel = Microsoft.Office.Interop.Excel 

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

wBook = excel.Workbooks.Add(System.Reflection.Missing.Value) 
wSheet = wBook.Sheets("sheet1") 

    With wBook 
.Sheets("Sheet1").Select() 
.Sheets(1).Name = "NameYourSheet" 
End With 


For i = 0 To DataGrid1.RowCount - 1 
For j = 0 To DataGrid1.ColumnCount - 1 
wSheet.Cells(i + 1, j + 1).value = DataGrid1.Rows(i).Cells(j).Value.tosring 
Next j 
Next i 

wSheet.Columns.AutoFit() 
+0

파일이 처음으로 생성되었는지 확인하십시오. if System.IO.Directory.Exists (tempPath) = False Then System.IO.Directory.CreateDirectory (tempPath) If System.IO.File.Exists (strFileName) = False Then System.IO .File.Create (strFileName) End If End If' 여기서 strFileName은 파일 이름이고 tempPath는 Excel 파일의 폴더입니다. – Manny265

+0

Microsoft.Office.Interop.Excel을 사용하지 않고 tp Excel을 내보내는 방법은 무엇입니까? – Elyor

1
Private Sub btnExportToExcel_Click(sender As Object, e As EventArgs) Handles btnExportToExcel.Click 

     Dim xlApp As Excel.Application = New Excel.Application 

     xlApp.SheetsInNewWorkbook = 1 

     Dim xlWorkBook As Excel.Workbook = xlApp.Workbooks.Add 
     Dim xlWorkSheet As Excel.Worksheet = xlWorkBook.Worksheets.Item(1) 

     xlWorkSheet.Name = "Example_Export" 

     For nRow = 0 To dgvDataToExport.Rows.Count - 1 

      For nCol = 0 To dgvDataToExport.Columns.Count - 1 
       xlWorkSheet.Cells(nRow + 1, nCol + 1) = dgvDataToExport.Rows(nRow).Cells(nCol).Value 
      Next nCol 

     Next nRow 

     xlApp.DisplayAlerts = False 

     xlWorkBook.SaveAs("C:\Example.xlsx", Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _ 
          Excel.XlSaveAsAccessMode.xlNoChange, Excel.XlSaveConflictResolution.xlLocalSessionChanges) 

     xlWorkBook.Close() 
     xlApp.Quit() 

    End Sub 
0

가 시도하려고 시도

 If Not dgv.RowCount = 0 Then 
      Dim folderBrowser As New FolderBrowserDialog 
      folderBrowser.Description = "Select location to save the report" 
      Dim filepath1 As String = "" 
      If (folderBrowser.ShowDialog() = DialogResult.OK) Then 
       filepath1 = folderBrowser.SelectedPath 
      Else 
       Exit Sub 
      End If 

      Dim xlApp As Microsoft.Office.Interop.Excel.Application 
      Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook 
      Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet 
      Try 

       Dim misValue As Object = System.Reflection.Missing.Value 
       Dim i As Integer 
       Dim j As Integer 
       xlApp = New Microsoft.Office.Interop.Excel.ApplicationClass 
       xlWorkBook = xlApp.Workbooks.Add(misValue) 
       xlWorkSheet = xlWorkBook.Sheets("sheet1") 
       '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
       Dim titleStyle As Excel.Style = xlWorkSheet.Application.ActiveWorkbook.Styles.Add("NewStyle1") 
       titleStyle.Font.Bold = True 
       titleStyle.Font.Size = "18" 
       titleStyle.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red) 

       xlWorkSheet.Cells(2, 2) = "Employee Payment Report" 
       xlWorkSheet.Cells(2, 4) = DateAndTime.Now.ToString("dd/MM/yyyy") 
       xlWorkSheet.Cells(2, 2).Style = "NewStyle1" 
       xlWorkSheet.Cells(2, 4).Style = "NewStyle1" 
       '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 

       '====================================================================================================== 
       Dim headerStyle As Excel.Style = xlWorkSheet.Application.ActiveWorkbook.Styles.Add("NewStyle") 
       headerStyle.Font.Bold = True 
       headerStyle.Font.Size = "12" 
       headerStyle.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Brown) 

       For k = 1 To dgv.Columns.Count 
        xlWorkSheet.Cells(4, k) = dgv.Columns(k - 1).HeaderText 
        xlWorkSheet.Cells(4, k).Style = "NewStyle" 

       Next 
       '======================================================================================================= 
       Dim str As String = "" 
       Dim l As Integer = 1 
       j = 6 
       Dim amt As Double = 0.0 
       For i = 0 To dgv.RowCount - 1 
        amt = amt + dgv.Rows(i).Cells(4).Value 
        For m = 0 To dgv.ColumnCount - 1 
         xlWorkSheet.Cells(j, l) = dgv(m, i).Value.ToString() 
         str = dgv(m, i).Value.ToString() 
         l = l + 1 
        Next 
        j = j + 1 
        l = 1 
       Next 
       '====================================================================================================== 
       Dim lastStyle As Excel.Style = xlWorkSheet.Application.ActiveWorkbook.Styles.Add("NewStyle2") 
       lastStyle.Font.Bold = True 
       lastStyle.Font.Size = "12" 
       lastStyle.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Blue) 
       Dim c As Integer = dgv.ColumnCount 
       xlWorkSheet.Cells(j + 2, c - 1) = "Total Amount" 
       xlWorkSheet.Cells(j + 2, c) = amt.ToString 
       xlWorkSheet.Cells(j + 2, c - 1).Style = "NewStyle2" 
       xlWorkSheet.Cells(j + 2, c).Style = "NewStyle2" 
       '======================================================================================================= 
       xlWorkSheet.SaveAs(filepath1 + "\EmployeePaymentReport.xlsx") 
       xlWorkBook.Close() 
       xlApp.Quit() 

       cls.releaseObject(xlApp) 
       cls.releaseObject(xlWorkBook) 
       cls.releaseObject(xlWorkSheet) 

       MsgBox("You can find the file at " + filepath1 + "\EmployeePaymentReport.xlsx") 
      Catch ex As Exception 
       MsgBox(ex.Message) 
       For Each Process In System.Diagnostics.Process.GetProcessesByName("EXCEL") 
        If Process.MainModule.ModuleName.ToUpper().Equals("EXCEL.EXE") Then 
         Process.Kill() 
        End If 
       Next 
      End Try 
     Else 
      Exit Sub 
     End If 
    Catch ex As Exception 

    End Try 
End Sub 
1

함께 시도해보십시오.

Sub create_excel(sender As Object, e As EventArgs) 
    Dim strFileName As string 
    Dim tw As New StringWriter() 
    Dim hw As New HtmlTextWriter(tw)  

    strFileName = "some_excel_from_datagrid.xls" 
    Response.ContentType = "application/vnd.msexcel" 
    Response.AddHeader("Content-Disposition", "attachment; filename=" & strFileName) 
    Response.Charset = "UTF-8" 
    Response.ContentEncoding = Encoding.Default 

    DataGridID.RenderControl(hw) 

    Response.Write(tw.ToString()) 
    Response.End() 
End Sub