1 Previous Next 

OpenXml: Create an Excel SpreadSheet (Open XML Format)


Office 2007 saves office documents in a new Open XML format.  This new office format is basically a zip file with xml inside it.  John Tunnicliffe has created an ExcelPackage class for creating excel documents. You can download it from the CodePlex Website. It uses the .Net 3.0 package class for creating the excel files.  Here is a sample that uses the ExcelPackage class.  Add Imports OpenOfficeXml to the top of the code file.

        If IO.File.Exists("Test.xlsx") Then IO.File.Delete("Test.xlsx")
        Dim fi As New IO.FileInfo("Test.xlsx")
        Using pack As New ExcelPackage(fi)
            Dim ws As ExcelWorksheet = pack.Workbook.Worksheets.Add("DataGridView")
            ws.Cell(1, 1).Value = "Product Name"
            ws.Column(1).Width = 30
            ws.Cell(1, 2).Value = "Price"
            ws.Column(2).Width = 10

            For r As Integer = 0 To dt.Rows.Count - 1
                For c As Integer = 0 To DataGridView1.Columns.Count - 1
                    ws.Cell(r + 2, c + 1).Value = DataGridView1.Item(c, r).Value.ToString.Replace("'"c, "")
                Next
            Next
            pack.Workbook.Properties.Author = "Ken Tucker"
            pack.Workbook.Properties.Title = "DataGridView Export"
            pack.Save()
        End Using
        MessageBox.Show("Done")




1 Previous Next