Excel spreadsheet library for C#/VB.NET

ExpertXls Excel Spreadsheet Library for .NET

Create Excel Spreadsheets in ASP.NET / VB.NET

Load/Get Data To/From an Excel Worksheet Using ExpertXls Excel Library for .NET

This sample shows how to import data from.NET DataTable or DataView object to an Excel worksheet and how to get the data from an Excel worksheet into a .NET DataTable or DataView object.
To create the Excel workbook first select the format of the generated workbook and press the Create Workbook button. The Excel workbook will be created on the server and sent as an attachment to the browser. You will be prompted to open the generated workbook in an external viewer. ExpertXls library can generate both XLS and XLSX files.
Workbook Format:
Create Workbook Button Create Excel Workbook
Source Code:

Imports ExpertXls.ExcelLib
Imports System.Drawing

Partial Class LoadGetDataTable
    Inherits System.Web.UI.Page

    Protected Sub lnkBtnCreateWorkbook_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkBtnCreateWorkbook.Click
        ' load an existing Excel file to a temporary workbook

        ' create the Excel stream
        Dim dataFilePath As String = System.IO.Path.Combine(Server.MapPath("~"), "Data\awemployees.xls")
        Dim sourceXlsDataStream As System.IO.FileStream = New System.IO.FileStream(dataFilePath, System.IO.FileMode.Open)

        Dim tempWorkbook As ExcelWorkbook = New ExcelWorkbook(sourceXlsDataStream)
        Dim tempWorksheet As ExcelWorksheet = tempWorkbook.Worksheets.Item(0)

        ' get the data from the used range of the temporary workbook to a .NET DataTable object
        Dim exportedDataTable As System.Data.DataTable = tempWorksheet.GetDataTable(tempWorksheet.UsedRange, True)

        'close the temporary workbook
        tempWorkbook.Close()
        'close the data stream
        sourceXlsDataStream.Close()

        ' Create the workbook in which the data from the DataTable will be loaded
        Dim workbookFormat As ExcelWorkbookFormat
        If radioXlsFormat.Checked Then
            workbookFormat = ExcelWorkbookFormat.Xls_2003
        Else
            workbookFormat = ExcelWorkbookFormat.Xlsx_2007
        End If

        ' create the workbook in the desired format with a single worksheet
        Dim workbook As ExcelWorkbook = New ExcelWorkbook(workbookFormat)

        ' get the first worksheet in the workbook
        Dim worksheet As ExcelWorksheet = workbook.Worksheets.Item(0)

        ' set the default worksheet name
        worksheet.Name = "Data Loaded from a DataTable"

        ' load data from DataTable into the worksheet
        worksheet.LoadDataTable(exportedDataTable, 5, 1, True)

        ' customize the workbook

        ' set the license key before saving the workbook
        'workbook.LicenseKey = "your license key here";

        ' set workbook description properties
        workbook.DocumentProperties.Subject = "Load or Get Data from a .NET DataTable"
        workbook.DocumentProperties.Comments = "Load/Get data to/from an Excel worksheet using ExpertXls Excel library for .NET"

        ' CREATE CUSTOM WORKBOOK STYLES

        ' Add a style used for the cells in the worksheet title area

        Dim titleStyle As ExcelCellStyle = workbook.Styles.AddStyle("WorksheetTitleStyle")
        ' center the text in the title area
        titleStyle.Alignment.HorizontalAlignment = ExcelCellHorizontalAlignmentType.Left
        titleStyle.Alignment.VerticalAlignment = ExcelCellVerticalAlignmentType.Center
        ' set the title area borders
        titleStyle.Borders.Item(ExcelCellBorderIndex.Bottom).Color = Color.Green
        titleStyle.Borders.Item(ExcelCellBorderIndex.Bottom).LineStyle = ExcelCellLineStyle.Medium
        titleStyle.Borders.Item(ExcelCellBorderIndex.Top).Color = Color.Green
        titleStyle.Borders.Item(ExcelCellBorderIndex.Top).LineStyle = ExcelCellLineStyle.Medium
        titleStyle.Borders.Item(ExcelCellBorderIndex.Left).Color = Color.Green
        titleStyle.Borders.Item(ExcelCellBorderIndex.Left).LineStyle = ExcelCellLineStyle.Medium
        titleStyle.Borders.Item(ExcelCellBorderIndex.Right).Color = Color.Green
        titleStyle.Borders.Item(ExcelCellBorderIndex.Right).LineStyle = ExcelCellLineStyle.Medium
        If workbookFormat = ExcelWorkbookFormat.Xls_2003 Then
            ' set the solid fill for the title area range with a custom color
            titleStyle.Fill.FillType = ExcelCellFillType.SolidFill
            titleStyle.Fill.SolidFillOptions.BackColor = Color.FromArgb(255, 255, 204)
        Else
            ' set the gradient fill for the title area range with a custom color
            titleStyle.Fill.FillType = ExcelCellFillType.GradientFill
            titleStyle.Fill.GradientFillOptions.Color1 = Color.FromArgb(255, 255, 204)
            titleStyle.Fill.GradientFillOptions.Color2 = Color.White
        End If
        ' set the title area font 
        titleStyle.Font.Size = 14
        titleStyle.Font.Bold = True
        titleStyle.Font.UnderlineType = ExcelCellUnderlineType.Single


        ' Add a style used for the data table header

        Dim dataHeaderStyle As ExcelCellStyle = workbook.Styles.AddStyle("DataHeaderStyle")
        dataHeaderStyle.Font.Size = 10
        dataHeaderStyle.Font.Bold = True
        dataHeaderStyle.Alignment.VerticalAlignment = ExcelCellVerticalAlignmentType.Center
        dataHeaderStyle.Alignment.HorizontalAlignment = ExcelCellHorizontalAlignmentType.Left
        dataHeaderStyle.Fill.FillType = ExcelCellFillType.SolidFill
        dataHeaderStyle.Fill.SolidFillOptions.BackColor = Color.LightBlue
        dataHeaderStyle.Borders.Item(ExcelCellBorderIndex.Bottom).LineStyle = ExcelCellLineStyle.Thin
        dataHeaderStyle.Borders.Item(ExcelCellBorderIndex.Top).LineStyle = ExcelCellLineStyle.Thin
        dataHeaderStyle.Borders.Item(ExcelCellBorderIndex.Left).LineStyle = ExcelCellLineStyle.Thin
        dataHeaderStyle.Borders.Item(ExcelCellBorderIndex.Right).LineStyle = ExcelCellLineStyle.Thin

        ' WORKSHEET PAGE SETUP

        ' set worksheet paper size and orientation, margins, header and footer
        worksheet.PageSetup.PaperSize = ExcelPagePaperSize.PaperA4
        worksheet.PageSetup.Orientation = ExcelPageOrientation.Landscape
        worksheet.PageSetup.LeftMargin = 1
        worksheet.PageSetup.RightMargin = 1
        worksheet.PageSetup.TopMargin = 1
        worksheet.PageSetup.BottomMargin = 1

        ' add header and footer

        'display a logo image in the left part of the header
        Dim imagesPath As String = System.IO.Path.Combine(Server.MapPath("~"), "Images")
        Dim logoImg As System.Drawing.Image = System.Drawing.Image.FromFile(System.IO.Path.Combine(imagesPath, "logo.jpg"))
        worksheet.PageSetup.LeftHeaderFormat = "&G"
        worksheet.PageSetup.LeftHeaderPicture = logoImg
        ' display worksheet name in the right part of the header
        worksheet.PageSetup.RightHeaderFormat = "&A"

        ' add worksheet header and footer
        ' display the page number in the center part of the footer
        worksheet.PageSetup.CenterFooterFormat = "&P"
        ' display the workbook file name in the left part of the footer
        worksheet.PageSetup.LeftFooterFormat = "&F"
        ' display the current date in the right part of the footer
        worksheet.PageSetup.RightFooterFormat = "&D"

        ' WRITE THE WORKSHEET TOP TITLE

        ' merge the cells in the range to create the title area 
        worksheet.Item("A2:N3").Merge()
        ' gets the merged range containing the top left cell of the range
        Dim titleRange As ExcelRange = worksheet.Item("A2").MergeArea
        ' set the text of title area
        worksheet.Item("A2").Text = "Load/Get data to/from an Excel Worksheet"

        ' set a row height of 18 points for each row in the range
        titleRange.RowHeightInPoints = 18
        ' set the worksheet top title style
        titleRange.Style = titleStyle


        worksheet.Item("A5:N5").Style = dataHeaderStyle
        worksheet.Item("A5:N5").RowHeightInPoints = 20

        ' lock the data table header
        worksheet.Item("A6").FreezePanes()

        ' autofit column width
        worksheet.AutofitColumns()

        ' SAVE THE WORKBOOK

        ' Save the Excel document in the current HTTP response stream

        Dim outFileName As String
        If workbookFormat = ExcelWorkbookFormat.Xls_2003 Then
            outFileName = "LoadGetDataTable.xls"
        Else
            outFileName = "LoadGetDataTable.xlsx"
        End If

        Dim httpResponse As System.Web.HttpResponse = System.Web.HttpContext.Current.Response

        ' Prepare the HTTP response stream for saving the Excel document

        ' Clear any data that might have been previously buffered in the output stream
        httpResponse.Clear()

        ' Set output stream content type for Excel 97-2003 (.xls) or Excel 2007-2013 (.xlsx)
        If workbookFormat = ExcelWorkbookFormat.Xls_2003 Then
            httpResponse.ContentType = "Application/x-msexcel"
        Else
            httpResponse.ContentType = "Application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        End If

        ' Add the HTTP header to announce the Excel document either as an attachment or inline
        httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", outFileName))

        ' Save the workbook to the current HTTP response output stream
        ' and close the workbook after save to release all the allocated resources
        Try
            workbook.Save(httpResponse.OutputStream)
        Catch ex As Exception
            ' report any error that might occur during save
            Session.Item("ErrorMessage") = ex.Message
            Response.Redirect("ErrorPage.aspx")
        Finally
            ' close the workbook and release the allocated resources
            workbook.Close()

            ' Dispose the Image object

            If Not logoImg Is Nothing Then
                logoImg.Dispose()
            End If

        End Try

        ' End the response and finish the execution of this page
        httpResponse.End()

    End Sub
End Class

ExpertXls Excel Spreadsheet Library for .NET