Convert Excel file into CSV with Microsoft Office Interop library using C# and VB.Net in ASP.Net

Last Reply one year ago By dharmendr

Posted one year ago

I have tried  one code It will take time I need simple way. 

In my Excel file have 66k records. 

there any simple way to convert .xls file to .csv file? (Excel)

 

Posted one year ago

Hi amar,

Refer the below sample function. For this i have used Microsoft.Office.Interop.Excel library.

C#

using Excel = Microsoft.Office.Interop.Excel;

public void ExcelToCSV(string sourceFile,string destinationFile)
{
    Type officeType = Type.GetTypeFromProgID("Excel.Application");
    if (officeType == null)
    {
        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('Excel is not installed in the machine')", true);
    }
    else
    {
        Excel.Application app = new Excel.Application();
        app.DisplayAlerts = false;
        // Open Excel Workbook for conversion.
        Excel.Workbook excelWorkbook = app.Workbooks.Open(sourceFile);
        // Save file as CSV file.
        excelWorkbook.SaveAs(destinationFile, Excel.XlFileFormat.xlCSV);
        // Close the Workbook.
        excelWorkbook.Close();
        // Quit Excel Application.
        app.Quit();
    }
}

VB.Net

Imports Excel = Microsoft.Office.Interop.Excel

Public Sub ExcelToCSV(sourceFile As String, destinationFile As String)
    Dim officeType As Type = Type.GetTypeFromProgID("Excel.Application")
    If officeType Is Nothing Then
        ClientScript.RegisterClientScriptBlock(Me.[GetType](), "", "alert('Excel is not installed')", True)
    Else
        Dim app As New Excel.Application()
        app.DisplayAlerts = False
        ' Open Excel Workbook for conversion.
        Dim excelWorkbook As Excel.Workbook = app.Workbooks.Open(sourceFile)
        ' Save file as CSV file.
        excelWorkbook.SaveAs(destinationFile, Excel.XlFileFormat.xlCSV)
        ' Close the Workbook.
        excelWorkbook.Close()
        ' Quit Excel Application.
        app.Quit()
    End If
End Sub