【问题标题】:DataGrid export to excel数据网格导出到 excel
【发布时间】:2023-03-30 12:55:01
【问题描述】:

我有一个DataGrid control,里面填满了data set。

我没有在 DataGrid 控件中显示数据集的所有字段。

我想从我的DataGrid 创建一个excel file

如何解决?

(窗口窗体,vb net 1.1

【问题讨论】:

  • 你想从datagrid导出excel吗?

标签: vb.net datagrid .net-1.1


【解决方案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

【讨论】:

    【解决方案2】:

    试试

            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
    

    【讨论】:

      【解决方案3】:
      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
      

      【讨论】:

        【解决方案4】:

        试试这个 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()
        

        【讨论】:

        • 还检查文件是否已创建,如果没有,则使用 ` 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文件所在的文件夹
        • 如何在不使用Microsoft.Office.Interop.Excel的情况下导出tp excel?
        【解决方案5】:

        也许在这项主要工作中。

          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();
        
                    }
        

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-07
        • 1970-01-01
        相关资源
        最近更新 更多