Datagridview vb net and excel

Excel Method

This method is different than many you will see. Others use a loop to write each cell and write the cells with text data type.

This method creates an object array from a DataTable or DataGridView and then writes the array to Excel. This means I can write to Excel without a loop and retain data types.

I extracted this from my library and I think I changed it enough to work with this code only, but more minor tweaking might be necessary. If you get errors just let me know and I’ll correct them for you. Normally, I create an instance of my class and call these methods. If you would like to use my library then use this link to download it and if you need help just let me know.
https://zomp.co/Files.aspx?ID=zExcel


After copying the code to your solution you will use it like this.

In your button code add this and change the names to your controls.

WriteDataGrid("Sheet1", grid)

To open your file after exporting use this line

System.Diagnostics.Process.Start("The location and filename of your file")

In the WriteArray method you’ll want to change the line that saves the workbook to where you want to save it. Probably makes sense to add this as a parameter.

wb.SaveAs("C:MyWorkbook.xlsx")


Public Function WriteArray(Sheet As String, ByRef ObjectArray As Object(,)) As String
    Try
        Dim xl As Excel.Application = New Excel.Application
        Dim wb As Excel.Workbook = xl.Workbooks.Add()
        Dim ws As Excel.Worksheet = wb.Worksheets.Add()
        ws.Name = Sheet
        Dim range As Excel.Range = ws.Range("A1").Resize(ObjectArray.GetLength(0), ObjectArray.GetLength(1))
        range.Value = ObjectArray

        range = ws.Range("A1").Resize(1, ObjectArray.GetLength(1) - 1)

        range.Interior.Color = RGB(0, 70, 132)  'Con-way Blue
        range.Font.Color = RGB(Drawing.Color.White.R, Drawing.Color.White.G, Drawing.Color.White.B)
        range.Font.Bold = True
        range.WrapText = True

        range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
        range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter

        range.Application.ActiveWindow.SplitColumn = 0
        range.Application.ActiveWindow.SplitRow = 1
        range.Application.ActiveWindow.FreezePanes = True

        wb.SaveAs("C:MyWorkbook.xlsx")
        wb.CLose()
        xl.Quit()
        xl = Nothing
        wb = Nothing
        ws  = Nothing
        range = Nothing
        ReleaseComObject(xl)
        ReleaseComObject(wb)
        ReleaseComObject(ws)
        ReleaseComObject(range)

        Return ""
    Catch ex As Exception
        Return "WriteArray()" & Environment.NewLine & Environment.NewLine & ex.Message
    End Try
End Function

Public Function WriteDataGrid(SheetName As String, ByRef dt As DataGridView) As String
        Try
            Dim l(dt.Rows.Count + 1, dt.Columns.Count) As Object
            For c As Integer = 0 To dt.Columns.Count - 1
                l(0, c) = dt.Columns(c).HeaderText
            Next

            For r As Integer = 1 To dt.Rows.Count
                For c As Integer = 0 To dt.Columns.Count - 1
                    l(r, c) = dt.Rows(r - 1).Cells(c)
                Next
            Next

            Dim errors As String = WriteArray(SheetName, l)
            If errors <> "" Then
                Return errors
            End If

            Return ""
        Catch ex As Exception
            Return "WriteDataGrid()" & Environment.NewLine & Environment.NewLine & ex.Message
        End Try
    End Function


 Public Function WriteDataTable(SheetName As String, ByRef dt As DataTable) As String
        Try
            Dim l(dt.Rows.Count + 1, dt.Columns.Count) As Object
            For c As Integer = 0 To dt.Columns.Count - 1
                l(0, c) = dt.Columns(c).ColumnName
            Next

            For r As Integer = 1 To dt.Rows.Count
                For c As Integer = 0 To dt.Columns.Count - 1
                    l(r, c) = dt.Rows(r - 1).Item(c)
                Next
            Next

            Dim errors As String = WriteArray(SheetName, l)
            If errors <> "" Then
                Return errors
            End If

            Return ""
        Catch ex As Exception
            Return "WriteDataTable()" & Environment.NewLine & Environment.NewLine & ex.Message
        End Try
    End Function

I actually don’t use this method in my Database program because it’s a slow method when you have a lot of rows/columns. I instead create a CSV from the DataGridView. Writing to Excel with Excel Automation is only useful if you need to format the data and cells otherwise you should use CSV. You can use the code after the image for CSV export.


CSV Method

Private Sub DataGridToCSV(ByRef dt As DataGridView, Qualifier As String)  
        Dim TempDirectory As String = "A temp Directory"  
        System.IO.Directory.CreateDirectory(TempDirectory)
        Dim oWrite As System.IO.StreamWriter
        Dim file As String = System.IO.Path.GetRandomFileName & ".csv"
        oWrite = IO.File.CreateText(TempDirectory & "" & file)

        Dim CSV As StringBuilder = New StringBuilder()

        Dim i As Integer = 1
        Dim CSVHeader As StringBuilder = New StringBuilder()
        For Each c As DataGridViewColumn In dt.Columns
            If i = 1 Then
                CSVHeader.Append(Qualifier & c.HeaderText.ToString() & Qualifier)
            Else
                CSVHeader.Append("," & Qualifier & c.HeaderText.ToString() & Qualifier)
            End If
            i += 1
        Next

        'CSV.AppendLine(CSVHeader.ToString())
        oWrite.WriteLine(CSVHeader.ToString())
        oWrite.Flush()

        For r As Integer = 0 To dt.Rows.Count - 1

            Dim CSVLine As StringBuilder = New StringBuilder()
            Dim s As String = ""
            For c As Integer = 0 To dt.Columns.Count - 1
                If c = 0 Then
                    'CSVLine.Append(Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier)
                    s = s & Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier
                Else
                    'CSVLine.Append("," & Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier)
                    s = s & "," & Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier
                End If

            Next
            oWrite.WriteLine(s)
            oWrite.Flush()
            'CSV.AppendLine(CSVLine.ToString())
            'CSVLine.Clear()
        Next

        'oWrite.Write(CSV.ToString())

        oWrite.Close()
        oWrite = Nothing    

        System.Diagnostics.Process.Start(TempDirectory & "" & file)   

        GC.Collect()

    End Sub

I have an application which opens one of several excel templates, fills a datagrid view with
Excel Named Range data.  Once the data is modified in the application I neet to save it to an excel spreadsheet.  I currently have the following working:

1.  This sub writes 2 columns of data (Ingredient) and (Result) from those named ranges and places them in the datagrid

Private Sub CboBoxTypeCofA_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CboBoxTypeCofA.SelectedIndexChanged

WorkbookTemplate =

«»
CofABook = «»

CboBoxTypeCofA.Visible = False

Select Case CboBoxTypeCofA.SelectedItem

Case Is = «Nothing»

GoTo Nextline

‘ Msgbox will go here to require change the jump to nextline is temporary

Case Is = «Flax Seed Oil»

        CofABook = «D:Flaxseedcofa_08.xls»

‘ Sets the name of the cofa template worksheet should be on a network mapped drive.

        WorkbookTemplate = «D:Flaxseedtemplate.xls»

Case Is = «PS Shakes»

        CofABook = «D:PSshakescofa_08.xls»

‘ Sets the name of the cofa template worksheet should be on a network mapped drive.

        WorkbookTemplate = «D:PSshakestemplate.xls»

Case Is = «Zone Shakes»

        CofABook = «D:Zoneshakescofa_08.xls»

        WorkbookTemplate = «D:zoneshakestemplate.xls»

End Select

NextLine:

‘ this code opens the template worksheet and writes the CofA results found named range to the datagrid for the user to update.

        connect = New System.Data.OleDb.OleDbConnection(«provider=Microsoft.Jet.OLEDB.4.0;» «data source=» & WorkbookTemplate & «;Extended Properties=Excel 8.0;»)

adapter = New System.Data.OleDb.OleDbDataAdapter(«select * from [Ingredient]», connect)

connect.Open()

adapter.Fill(dataset)

Me.DataGridView1.DataSource = dataset.Tables(0)

adapter.Fill(dataset.Tables(0))

adapter = New System.Data.OleDb.OleDbDataAdapter(«select * from [Found]», connect)

adapter.Fill(dataset)

Me.DataGridView1.DataSource = dataset.Tables(0)

adapter.Fill(dataset.Tables(0))

connect.Close()

2.  This code takes other named ranges (single data items) from the same workbook and places them in controls on the form for update.

oExcel = CreateObject(

«Excel.Application»)

‘ Create the template workbook object

oBook = oExcel.Workbooks.Open(WorkbookTemplate)

    TxtProductName.Text = oBook.names(«Productname»).referstorange.value

    TxtLotnum.Text = oBook.Names(«Lotnum»).RefersToRange.Value

    TxtQtyShipped.Text = oBook.names(«Qtyshipped»).referstorange.value

    OldYear = oBook.names(«Year»).referstorange.value

oExcel.workbooks.Close()

oExcel.Quit()

This code works and the only problem is that after running the code the excel application does not close.

Now I need to write the completed updates from the datagrid view and the other controls back into a workbook.

Ive been searching around but have not found the proper way to do this and how to kill the oexcel application in the code above.

Thanks

Wnewcomb

In this article I will explain with an example, how to export DataGridView data to Excel file with formatting i.e. Colors and Styles in Windows Forms (WinForms) Applications using C# and VB.Net.

DataGridView cannot be exported directly to Excel file and hence need to generate a DataTable and export the DataTable to Excel file.

The DataTable will be exported to a formatted Excel file using ClosedXml library which is a wrapper of OpenXml.

Database

I have made use of the following table Customers with the schema as follows.

Export DataGridView to Excel with Formatting using C# and VB.Net

I have already inserted few records in the table.

Export DataGridView to Excel with Formatting using C# and VB.Net

Note: You can download the database table SQL by clicking the download link below.

Download DocumentFormat.OpenXml and ClosedXml Libraries

You can download the libraries using the following download locations.

Note: The DLL files of both OpenXml and ClosedXml are present in the attached sample.

Form Controls

I have added a DataGridView and a Button to the Windows Form.

Export DataGridView to Excel with Formatting using C# and VB.Net

Namespaces

You will need to import the following namespaces.

C#

using System.IO;

using System.Data;

using ClosedXML.Excel;

using System.Data.SqlClient;

VB.Net

Imports System.IO

Imports System.Data

Imports ClosedXML.Excel

Imports System.Data.SqlClient

Populating DataGridView

Inside the Form Load event, the DataGridView is populated with records from Customers table.

C#

private void Form1_Load(object sender, EventArgs e)

{

    this.BindDataGridView();

}

private void BindDataGridView()

{

    string constring = @»Data Source=.SQL2014;Initial Catalog=AjaxSamples;Integrated Security=true»;

    using (SqlConnection con = new SqlConnection(constring))

    {

        using (SqlCommand cmd = new SqlCommand(«SELECT * FROM Customers», con))

        {

            cmd.CommandType = CommandType.Text;

            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))

            {

                using (DataTable dt = new DataTable())

                {

                    sda.Fill(dt);

                    dataGridView1.DataSource = dt;

                }

            }

        }

    }

}

VB.Net

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    Me.BindDataGridView()

End Sub

Private Sub BindDataGridView()

    Dim constring As String = «Data Source=.SQL2014;Initial Catalog=AjaxSamples;Integrated Security=true»

    Using con As New SqlConnection(constring)

        Using cmd As New SqlCommand(«SELECT * FROM Customers», con)

            cmd.CommandType = CommandType.Text

            Using sda As New SqlDataAdapter(cmd)

                Using dt As New DataTable()

                    sda.Fill(dt)

                    dataGridView1.DataSource = dt

                End Using

            End Using

        End Using

    End Using

End Sub

Export DataGridView to Excel with Formatting using C# and VB.Net

Exporting DataGridView data to Excel with formatting

Inside the Button Click event handler, first a DataTable is created with columns same as that of the DataGridView and a loop is executed over the DataGridView rows and all the data is added to the DataTable.

Then a Workbook object is created to which the DataTable is added as Worksheet using the Add method which accepts DataTable and the name of the Sheet as parameters.

Once the DataTable is added as a Worksheet to the Workbook, the formatting is done by first setting the Header row background color and then applying background colors to the rows and the alternating rows of the Excel file.

Finally the WorkBook is saved to the specified location on the disk.

C#

private void btnExportExcel_Click(object sender, EventArgs e)

{

    //Creating DataTable.

    DataTable dt = new DataTable();

    //Adding the Columns.

    foreach (DataGridViewColumn column in dataGridView1.Columns)

    {

        dt.Columns.Add(column.HeaderText, column.ValueType);

    }

    //Adding the Rows.

    foreach (DataGridViewRow row in dataGridView1.Rows)

    {

        dt.Rows.Add();

        foreach (DataGridViewCell cell in row.Cells)

        {

            dt.Rows[dt.Rows.Count — 1][cell.ColumnIndex] = cell.Value.ToString();

        }

    }

    //Exporting to Excel.

    string folderPath = «C:\Excel\»;

    if (!Directory.Exists(folderPath))

    {

        Directory.CreateDirectory(folderPath);

    }

    using (XLWorkbook wb = new XLWorkbook())

    {

        wb.Worksheets.Add(dt, «Customers»);

        //Set the color of Header Row.

        //A resembles First Column while C resembles Third column.

        wb.Worksheet(1).Cells(«A1:C1»).Style.Fill.BackgroundColor = XLColor.DarkGreen;

        for (int i = 1; i <= dt.Rows.Count; i++)

        {

            //A resembles First Column while C resembles Third column.

            //Header row is at Position 1 and hence First row starts from Index 2.

            string cellRange = string.Format(«A{0}:C{0}», i + 1);

            if (i % 2 != 0)

            {

                wb.Worksheet(1).Cells(cellRange).Style.Fill.BackgroundColor = XLColor.GreenYellow;

            }

            else

            {

                wb.Worksheet(1).Cells(cellRange).Style.Fill.BackgroundColor = XLColor.Yellow;

            }

        }

        //Adjust widths of Columns.

        wb.Worksheet(1).Columns().AdjustToContents();

        //Save the Excel file.

        wb.SaveAs(folderPath + «DataGridViewExport.xlsx»);

    }

}

VB.Net

Private Sub btnExportExcel_Click(sender As Object, e As EventArgs) Handles btnExportExcel.Click

    ‘Creating DataTable.

    Dim dt As New DataTable()

    ‘Adding the Columns.

    For Each column As DataGridViewColumn In dataGridView1.Columns

        dt.Columns.Add(column.HeaderText, column.ValueType)

    Next

    ‘Adding the Rows.

    For Each row As DataGridViewRow In dataGridView1.Rows

        dt.Rows.Add()

        For Each cell As DataGridViewCell In row.Cells

            dt.Rows(dt.Rows.Count — 1)(cell.ColumnIndex) = cell.Value.ToString()

        Next

    Next

    ‘Exporting to Excel.

    Dim folderPath As String = «C:Excel»

    If Not Directory.Exists(folderPath) Then

        Directory.CreateDirectory(folderPath)

    End If

    Using wb As New XLWorkbook()

        wb.Worksheets.Add(dt, «Customers»)

        ‘Set the color of Header Row.

        ‘A resembles First Column while C resembles Third column.

        wb.Worksheet(1).Cells(«A1:C1»).Style.Fill.BackgroundColor = XLColor.DarkGreen

        For i As Integer = 1 To dt.Rows.Count

            ‘A resembles First Column while C resembles Third column.

            ‘Header row is at Position 1 and hence First row starts from Index 2.

            Dim cellRange As String = String.Format(«A{0}:C{0}», i + 1)

            If i Mod 2 <> 0 Then

                wb.Worksheet(1).Cells(cellRange).Style.Fill.BackgroundColor = XLColor.GreenYellow

            Else

                wb.Worksheet(1).Cells(cellRange).Style.Fill.BackgroundColor = XLColor.Yellow

            End If

        Next

        ‘Adjust widths of Columns.

        wb.Worksheet(1).Columns().AdjustToContents()

        ‘Save the Excel file.

        wb.SaveAs(folderPath & «DataGridViewExport.xlsx»)

    End Using

End Sub

Screenshot

Export DataGridView to Excel with Formatting using C# and VB.Net

Downloads

Содержание

  1. How to export DataGridView to Excel file in C# and VB.NET
  2. Source code sample
  3. Step 1: Download and install EasyXLS Excel Library for .NET
  4. Step 2: Create a C# or VB.NET project
  5. Step 3: Include EasyXLS library into project
  6. Step 4: Run C# or VB.NET code that exports DataGridView to Excel
  7. Formatting cells
  8. See also:
  9. How to format Excel cells?
  10. How to use predefined cells format?
  11. Export DataGridView to XLSX, XLSB, XLSM and XLS files
  12. See also:
  13. How to export to XLSX file?
  14. How to export to XLSM file?
  15. How to export to XLSB file?
  16. How to export to XLS file?
  17. Export DataGridView to Excel file with multiple sheets
  18. See also:
  19. How to export to Excel file in C# and VB.NET?
  20. How to create multiple sheets?
  21. Export DataTable of DataGridView to Excel file
  22. See also:
  23. How to export DataTable to Excel file in C# and VB.NET?
  24. Getting started with EasyXLS Excel library
  25. How to export datagridview to excel using vb.net?
  26. 9 Answers 9
  27. How to Export DataGridView to Excel In VB.Net
  28. What is Visual Basic’s purpose?
  29. Steps How to Export DataGridView to Excel In VB.Net
  30. How to import Excel file to DataGridView in C# and VB.NET
  31. Source code sample
  32. Step 1: Download and install EasyXLS Excel Library for .NET
  33. Step 2: Create a C# or VB.NET project
  34. Step 3: Include EasyXLS library into project
  35. Step 4: Run C# or VB.NET code that imports Excel data to DataGridView
  36. Import Excel cell formatting to DataGridView
  37. Source code sample
  38. See also:
  39. Import Excel to GridView (Download open source code)
  40. How to format Excel cells?
  41. Import Excel file having one sheet to DataGridView
  42. Import Excel file having multiple sheets to DataGridView
  43. Import range of Excel cells to DataGridView
  44. VB.NET Save DataGridView to Excel with headers
  45. 2 answers

How to export DataGridView to Excel file in C# and VB.NET

EasyXLS™ library allows you to export a DataGridView to an Excel file. The exported data in cells can be formatted.

EasyXLS can be successfully used inclusively to export large Excel files having big volume of data with fast exporting time.

Table of contents

Source code sample

Step 1: Download and install EasyXLS Excel Library for .NET

To download the trial version of EasyXLS Excel Library, press the below button:

If you already own a license key, you may login and download EasyXLS from your account.

Step 2: Create a C# or VB.NET project

If don’t have a project, create one as ASP.NET web application, windows forms app, console application, class library or service.

Step 3: Include EasyXLS library into project

EasyXLS.dll must be added as reference to your project. EasyXLS.dll can be found after installing EasyXLS, in «Dot NET version» folder.

Step 4: Run C# or VB.NET code that exports DataGridView to Excel

The below example shows how to export DataGridView to Excel in C# and VB.NET from a winform windows application.

Formatting cells

EasyXLS™ enables you to format cells, rows and columns in order to set the fonts and colors.

See also:

How to format Excel cells?

How to use predefined cells format?

Export DataGridView to XLSX, XLSB, XLSM and XLS files

This code sample shows how to export a DataGridView to XLSX file. Similarly, you can export a DataGridView to XLS file using ExcelDocument. easy_WriteXLSFile_FromDataSet method or export DataGridView to XLSB file using ExcelDocument. easy_WriteXLSBFile_FromDataSet method.

See also:

How to export to XLSX file?

How to export to XLSM file?

How to export to XLSB file?

How to export to XLS file?

Export DataGridView to Excel file with multiple sheets

EasyXLS enables you to create multiple sheets for the Excel file and insert the DataGridView inside a specific sheet.

See also:

How to export to Excel file in C# and VB.NET?

How to create multiple sheets?

Export DataTable of DataGridView to Excel file

If the data source of the DataGridView is a DataTable, like in the above sample, the data can be also exported directly from the DataTable.

See also:

How to export DataTable to Excel file in C# and VB.NET?

Getting started with EasyXLS Excel library

To download the trial version of EasyXLS Excel Library, press the below button:

If you already own a license key, you may login and download EasyXLS from your account.

Источник

How to export datagridview to excel using vb.net?

I have a datagridview in vb.net that is filled up from the database. I’ve researched and I found out that there is no built in support to print directly from datagridview. I don’t want to use crystal report because I’m not familiar with it.

I’m planning to export it to excel to enable me to generate report from the datagridview.

Can you provide me ways to do this?

9 Answers 9

Code below creates Excel File and saves it in D: drive It uses Microsoft office 2007

FIRST ADD REFERRANCE (Microsoft office 12.0 object library ) to your project

Then Add code given bellow to the Export button click event-

Excel Method

This method is different than many you will see. Others use a loop to write each cell and write the cells with text data type.

This method creates an object array from a DataTable or DataGridView and then writes the array to Excel. This means I can write to Excel without a loop and retain data types.

I extracted this from my library and I think I changed it enough to work with this code only, but more minor tweaking might be necessary. If you get errors just let me know and I’ll correct them for you. Normally, I create an instance of my class and call these methods. If you would like to use my library then use this link to download it and if you need help just let me know.
https://zomp.co/Files.aspx?ID=zExcel

After copying the code to your solution you will use it like this.

In your button code add this and change the names to your controls.

To open your file after exporting use this line

System.Diagnostics.Process.Start(«The location and filename of your file»)

In the WriteArray method you’ll want to change the line that saves the workbook to where you want to save it. Probably makes sense to add this as a parameter.

I actually don’t use this method in my Database program because it’s a slow method when you have a lot of rows/columns. I instead create a CSV from the DataGridView. Writing to Excel with Excel Automation is only useful if you need to format the data and cells otherwise you should use CSV. You can use the code after the image for CSV export.

Источник

How to Export DataGridView to Excel In VB.Net

This tutorial is all about how to Export DataGridView Data to Excel in VB.Net. In this tutorial, you will expect that I will teach you everything you need to learn on how to Export DataGridView Data to excel using visual basic.net.

What is Visual Basic’s purpose?

The third-generation programming language was created to aid developers in the creation of Windows applications. It has a programming environment that allows programmers to write code in.exe or executable files. They can also utilize it to create in-house front-end solutions for interacting with huge databases. Because the language allows for continuing changes, you can keep coding and revising your work as needed.

However, there are some limits to the Microsoft Visual Basic download. If you want to make applications that take a long time to process, this software isn’t for you. That implies you won’t be able to use VB to create games or large apps because the system’s graphic interface requires a lot of memory and space. Furthermore, the language is limited to Microsoft and does not support other operating systems.

Please enable JavaScript

With this tutorial, it can answer the question raised in StackOverflow.

So let’s get started:

Steps How to Export DataGridView to Excel In VB.Net

Step 1: First, Open the Visual Basic, Select File on the menu, then click New and create a new project.

Step 2: Then a New Project Dialog will appear. You can rename your project, depending on what you like to name it. After that click OK.

Step 3: Design your form just like this one I’ve shown you below.
Drag a Datagridview and a Button from the toolbox.

Step 4: Add a reference to Microsoft Excel 12.0 Object Library, In the project menu click on ProjectAdd Reference – go to COM tab,
Add Microsoft Excel 12.0 Object Library

Step 5: After that, add the following references above the Public Class Form1 Line.

Step 6: Then add these following declarations below the Public Class Form1 line.

Step 7: Add this code to the form load event.

Step 8: Next, add this code to the export button.

Step 9: Finally, add the following code to save the excel file when closing the form.

Step 10: Click F5 to run your project.

Источник

How to import Excel file to DataGridView in C# and VB.NET

EasyXLS™ library allows you to import Excel data to DataGridView. The data can be imported from an Excel sheet or from the active Excel sheet. The entire sheet data or only data from ranges of cells can be imported.

EasyXLS can be successfully used to also import large Excel files having big volume of data with fast importing time.

Table of contents

Source code sample

Step 1: Download and install EasyXLS Excel Library for .NET

To download the trial version of EasyXLS Excel Library, press the below button:

If you already own a license key, you may login and download EasyXLS from your account.

Step 2: Create a C# or VB.NET project

If don’t have a project, create one as ASP.NET web application, windows forms app, console application, class library or service.

Step 3: Include EasyXLS library into project

EasyXLS.dll must be added as reference to your project. EasyXLS.dll can be found after installing EasyXLS, in «Dot NET version» folder.

Step 4: Run C# or VB.NET code that imports Excel data to DataGridView

The below example shows how to import Excel data to DataGridView in C# and VB.NET from a winform windows application.

Import Excel cell formatting to DataGridView

Importing also the cell formatting requires some changes to previous code in order to import not only data from the Excel file, but also the cell formatting styles. See below how the source code must be adjusted:

Source code sample

EasyXLS also offers some open source code that imports an Excel file to a GridView. The code shows how to import all cell data and formatting, conditional formatting and the charts.

See also:

Import Excel to GridView (Download open source code)

How to format Excel cells?

Import Excel file having one sheet to DataGridView

Importing the Excel file data to DataGridView, if the Excel file has only one sheet, is the easiest approach. The Excel data can be imported with one single line of code using:
— ExcelDocument. easy_ReadXLSXActiveSheet_AsDataSet method for XLSX file
— ExcelDocument. easy_ReadXLSBActiveSheet_AsDataSet method for XLSB file
— ExcelDocument. easy_ReadXLSActiveSheet_AsDataSet method for XLS file

The first code sample shows how to achieve this goal.

Import Excel file having multiple sheets to DataGridView

There are three approaches for importing data from an Excel file with multiple sheets.

I. Usually the first sheet is the active sheet inside an Excel file. If this is your case or if you are importing data from another active sheet use:
— ExcelDocument. easy_ReadXLSXActiveSheet_AsDataSet method for XLSX file
— ExcelDocument. easy_ReadXLSBActiveSheet_AsDataSet method for XLSB file
— ExcelDocument. easy_ReadXLSActiveSheet_AsDataSet method for XLS file

II. For importing data from an Excel sheet and the name of the sheet is known, EasyXLS recommends the use of:
— ExcelDocument. easy_ReadXLSXSheet_AsDataSet method for XLSX file
— ExcelDocument. easy_ReadXLSBSheet_AsDataSet method for XLSB file
— ExcelDocument. easy_ReadXLSSheet_AsDataSet method for XLS file

III. For importing data from an Excel sheet and the name of the sheet is not known, the first step is to find the sheet by reading the Excel file using:
— ExcelDocument.easy_LoadXLSXFile method for XLSX file
— ExcelDocument.easy_LoadXLSBFile method for XLSB file
— ExcelDocument.easy_LoadXLSFile method for XLS file

Then, import the sheet data in DataGridView using ExcelDocument. easy_ReadExcelWorksheet_AsDataSet method.

Import range of Excel cells to DataGridView

EasyXLS enables you to import Excel data to DataGridView either from the entire sheet or from a range of cells. Importing only a range of cells is a very useful option especially for large Excel files because it reduces the speed of the import process.

In order to import multiple cell ranges at once from Excel sheet, the range parameter must be passed to the method as union of ranges (multiple ranges separated by comma).

All the methods that allow importing Excel to DataSet have parameters that permit importing only ranges of cells.

Источник

I would like to export / Save DataGridView to Excel. The below code works but it does not export DGV headers.

Hi @jim brown ,
May I know whether your issue has been solved or not? Please let me know if you need further assistance.

2 answers

A better way is shown in the following code sample which uses a completely free NuGet package SpreadSheetLight which does not require Excel to be installed.

Is there a way to export with datagrid view colors and formatting. I mean exactly what i see in datagridview

Hi @jim brown ,
Here’s an example you can refer to.

Best Regards,
Xingyu Zhao
*
If the answer is helpful, please click «Accept Answer» and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Источник

Понравилась статья? Поделить с друзьями:
  • Dataframe to excel without index
  • Dataformat error входные данные не удалось распознать как допустимый документ excel сведения binary
  • Database to word document
  • Database to use with excel
  • Database in excel format