Click here to Skip to main content
15,881,173 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Dear All,
I'm having one datatable, i want to export this datatable's values to .xls file(Excel file) without referring the excel assemblies because i didn't install MS Excel in my pc but instead i've Open office software to process xls files.
So anyone give me the idea how to export my Datatable to .xls file format.

Regards,
BlueSathish
Posted
Updated 12-Jul-16 6:04am

I can recommend ClosedXml. It's open source and easy to use..

You download it from codeplex and add reference in your project.

C#
var wb = new XLWorkbook();
wb.Worksheets.Add(yourDataTable);
wb.SaveAs("myExcelFile.xlsx");


PS.. ClosedXml only supports .xlsx!
 
Share this answer
 
v2
Comments
bluesathish 23-Jul-12 6:43am    
Hi AlluvialDeposit,
thanks for your reply, but i want to export it into .xls file only and also i dont want to add any external component like this ClosedXml, Is there any possibility to do this by vb.net codings?
barryblessing 7-Nov-13 20:56pm    
Sorry if this is too late an answer, but use ClosedXML to export to .XLSX format. Then use Excel 2003 (or higher) or OpenOffice Spreadsheet to save the .XLSX file to .XLS format. The ClosedXML library is very effective.
StianSandberg 23-Jul-12 6:47am    
without external component.... good luck. I don't think you want to even try to do that in xls-format.. You need a 3rd party library, but that does not mean you will have to install MS Office on your server.
bluesathish 23-Jul-12 6:55am    
ok But i've Open Office software, how can i use its assemblies to export?, we usually doing using Microsoft.Office.Interop, in Open office do we've similar assemblies to do the same?
StianSandberg 23-Jul-12 7:00am    
http://blog.nkadesign.com/2008/net-working-with-openoffice-3/
VB
Imports Microsoft
Imports Microsoft.Office.Interop


and add reference dll "Microsoft.Office.Interop.Excel"

function to export data is given below

VB
''' <summary>
    ''' Write Excel file as given file name with given data.
    ''' </summary>
    ''' <param name="a_sFilename">full file name for create excel file.</param>
    ''' <param name="a_sData">data in dataset to be fill in excel shhet.</param>
    ''' <param name="a_sFileTitle">Title of Excel file.</param>
    ''' <param name="a_sErrorMessage">output parameter contains error message if error occurrs.</param>
    ''' <returns>bool</returns>
    Public Function ExportToExcel(ByVal a_sFilename As String, ByVal a_sData As DataSet, ByVal a_sFileTitle As String, ByRef a_sErrorMessage As String) As Boolean
        a_sErrorMessage = String.Empty
        Dim bRetVal As Boolean = False
        Dim dsDataSet As DataSet = Nothing
        Try
            dsDataSet = a_sData

            Dim xlObject As Excel.Application = Nothing
            Dim xlWB As Excel.Workbook = Nothing
            Dim xlSh As Excel.Worksheet = Nothing
            Dim rg As Excel.Range = Nothing
            Try
                xlObject = New Excel.Application()
                xlObject.AlertBeforeOverwriting = False
                xlObject.DisplayAlerts = False

                ''This Adds a new woorkbook, you could open the workbook from file also
                xlWB = xlObject.Workbooks.Add(Type.Missing)
                xlWB.SaveAs(a_sFilename, 56, Missing.Value, Missing.Value, Missing.Value, Missing.Value, _
                Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value)

                xlSh = DirectCast(xlObject.ActiveWorkbook.ActiveSheet, Excel.Worksheet)

                'Dim sUpperRange As String = "A1"
                'Dim sLastCol As String = "AQ"
                'Dim sLowerRange As String = sLastCol + (dsDataSet.Tables(0).Rows.Count + 1).ToString()

                For j = 0 To dsDataSet.Tables(0).Columns.Count - 1
                    xlSh.Cells(1, j + 1) = _
                        dsDataSet.Tables(0).Columns(j).ToString()
                    xlSh.Cells(1, j + 1).Font.Bold = True
                Next

                For i = 1 To dsDataSet.Tables(0).Rows.Count
                    For j = 0 To dsDataSet.Tables(0).Columns.Count - 1
                        xlSh.Cells(i + 1, j + 1) = _
                            dsDataSet.Tables(0).Rows(i - 1)(j).ToString()
                    Next
                Next
                xlSh.Columns.AutoFit()
                'rg = xlSh.Range(sUpperRange, sLowerRange)
                'rg.Value2 = GetData(dsDataSet.Tables(0))

                'xlSh.Range("A1", sLastCol & "1").Font.Bold = True
                'xlSh.Range("A1", sLastCol & "1").HorizontalAlignment = XlHAlign.xlHAlignCenter
                'xlSh.Range(sUpperRange, sLowerRange).EntireColumn.AutoFit()
               
                If String.IsNullOrEmpty(a_sFileTitle) Then
                    xlObject.Caption = "untitled"
                Else
                    xlObject.Caption = a_sFileTitle
                End If

                xlWB.Save()
                bRetVal = True
            Catch ex As System.Runtime.InteropServices.COMException
                If ex.ErrorCode = -2147221164 Then
                    a_sErrorMessage = "Error in export: Please install Microsoft Office (Excel) to use the Export to Excel feature."
                ElseIf ex.ErrorCode = -2146827284 Then
                    a_sErrorMessage = "Error in export: Excel allows only 65,536 maximum rows in a sheet."
                Else
                    a_sErrorMessage = (("Error in export: " & ex.Message) + Environment.NewLine & " Error: ") + ex.ErrorCode
                End If
            Catch ex As Exception
                a_sErrorMessage = "Error in export: " & ex.Message
            Finally
                Try
                    If xlWB IsNot Nothing Then
                        xlWB.Close(Nothing, Nothing, Nothing)
                    End If
                    xlObject.Workbooks.Close()
                    xlObject.Quit()
                    If rg IsNot Nothing Then
                        Marshal.ReleaseComObject(rg)
                    End If
                    If xlSh IsNot Nothing Then
                        Marshal.ReleaseComObject(xlSh)
                    End If
                    If xlWB IsNot Nothing Then
                        Marshal.ReleaseComObject(xlWB)
                    End If
                    If xlObject IsNot Nothing Then
                        Marshal.ReleaseComObject(xlObject)
                    End If

                Catch
                End Try
                xlSh = Nothing
                xlWB = Nothing
                xlObject = Nothing
                ' force final cleanup!
                GC.Collect()
                GC.WaitForPendingFinalizers()
            End Try
        Catch ex As Exception
            a_sErrorMessage = "Error in export: " & ex.Message
        End Try

        Return bRetVal
    End Function


try this code

Happy Coding!
:)
 
Share this answer
 
v2
Comments
StianSandberg 23-Jul-12 7:01am    
this code require Office installed on server.
bluesathish 23-Jul-12 7:06am    
yes, its not meet my needs.
bluesathish 23-Jul-12 7:05am    
Hi Aarti, Thanks for your reply,i don't have the excel in my pc. (read question clearly before you posting your solutions) Can you give me the idea to use by open office assemblies?
Aarti Meswania 23-Jul-12 7:08am    
I am not sure. but just try to add reference dll "Microsoft.Office.Interop.Excel" in your project if it's successfully added,
then If you do not have office installed in your pc still you will able to write data in excel file.
but you will just not open that file directly.
bluesathish 23-Jul-12 7:11am    
its successfully added to my project, but it needs Microsoft Excel COM reference. I got runtime errors.
C#
Public Function GridExport(ByVal DGV As DataGridView) As Boolean
    If DGV.RowCount > 0 Then
        Dim filename As String = Application.StartupPath & "\Export_" + Format(Now, "hhmmss").ToString + ".xls"
        DGV.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText
        DGV.SelectAll()
        IO.File.WriteAllText(filename, DGV.GetClipboardContent().GetText.TrimEnd)
        DGV.ClearSelection()
        Process.Start(filename)
        Return True
    Else
        Return False
    End If
End Function
 
Share this answer
 
Comments
Richard MacCutchan 12-Jul-16 12:11pm    
This question was posted 4 years ago. Please do not resurrect dead questions.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900