'How to convert .xls file to .xlsx using C# and without Microsoft Office installed?

I need help in converting a .xls file to .xlsx using C# and without using Microsoft Office.



Solution 1:[1]

With some coding work you can use the NPOI library to read the XLS data and write them back as XLSX.

The other way round (XLSX to XLS) is shown in Convert xlsx file to xls using NPOI in c#. That may be a good starting point to see the principle.

Solution 2:[2]

use below query,

private static string GetConnectionString()
    {
        Dictionary<string, string> props = new Dictionary<string, string>();

        // XLSX - Excel 2007, 2010, 2012, 2013
        props["Provider"] = "Microsoft.ACE.OLEDB.12.0;";
        props["Extended Properties"] = "Excel 12.0 XML";
        props["Data Source"] = @"D:\data\users\liran-fr\Desktop\Excel\Received\Orbotech_FW__ARTEMIS-CONTROL-AG__223227__0408141043__95546.xls";

        // XLS - Excel 2003 and Older
        //props["Provider"] = "Microsoft.Jet.OLEDB.4.0";
        //props["Extended Properties"] = "Excel 8.0";
        //props["Data Source"] = "C:\\MyExcel.xls";

        StringBuilder sb = new StringBuilder();

        foreach (KeyValuePair<string, string> prop in props)
        {
            sb.Append(prop.Key);
            sb.Append('=');
            sb.Append(prop.Value);
            sb.Append(';');
        }

        return sb.ToString();
    }

    private static DataSet ReadExcelFile()
    {
        DataSet ds = new DataSet();

        string connectionString = GetConnectionString();

        using (OleDbConnection conn = new OleDbConnection(connectionString))
        {
            conn.Open();
            OleDbCommand cmd = new OleDbCommand();
            cmd.Connection = conn;

            // Get all Sheets in Excel File
            DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

            // Loop through all Sheets to get data
            foreach (DataRow dr in dtSheet.Rows)
            {
                string sheetName = dr["TABLE_NAME"].ToString();

                //if (!sheetName.EndsWith("$"))
                //    continue;

                // Get all rows from the Sheet
                cmd.CommandText = "SELECT * FROM [" + sheetName + "]";

                DataTable dt = new DataTable();
                dt.TableName = sheetName;

                OleDbDataAdapter da = new OleDbDataAdapter(cmd);
                da.Fill(dt);

                ds.Tables.Add(dt);
            }

            cmd = null;
            conn.Close();
        }

        return ds;
    }
using (ExcelPackage epackage = new ExcelPackage())
        {
            ExcelWorksheet excel = epackage.Workbook.Worksheets.Add("ExcelTabName");
            DataSet ds = ReadExcelFile();
            DataTable dtbl = ds.Tables[0];
            excel.Cells["A1"].LoadFromDataTable(dtbl, true);
            System.IO.FileInfo file = new System.IO.FileInfo(@"D:\data\users\liran-fr\Desktop\Excel\Received\test.xlsx");
            epackage.SaveAs(file);
        }

Solution 3:[3]

I posted this answer that I was so impressed with, until I saw this link, which is way better and simpler:

I know this has been asked and answered, but here is what I borrowed from others... Sorry that I can't give credit as I don't know how gave me the idea, but in C#, create a process to copy the file from xls to xlsx. No fuss, no muss. This is in .Net Core 6.0 and o365.

Ultimately, the string you are running in the process (aka command prompt) should look similar to this:

"C:\Program Files (x86)\Microsoft Office\root\Office16\excelcnv.exe" -oice "\Share\Folder\Cash.xls" "\Share\Folder\Cash.xlsx"

public static class Xls2XlsxCmdProcess
{ 
    
    public static string processDirectory = @"C:\Program Files (x86)\Microsoft Office\root\Office16\";

    public static void ExecuteCommandSync(string pathToExe, string command)
    {
        
        var procStartInfo = new ProcessStartInfo(pathToExe, command)
        {
            WorkingDirectory = processDirectory,
            CreateNoWindow = false,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            RedirectStandardInput = true
        };

        var proc = new Process { StartInfo = procStartInfo };
        proc.Start();

        //proc.StandardInput.WriteLine(password);//If the app that requires a password or other params, they can be added here as a string.
        proc.StandardInput.Flush();

        // Get the output into a string
        string result = proc.StandardOutput.ReadToEnd();
        string error = proc.StandardError.ReadToEnd();

        Console.WriteLine(result);
        Console.WriteLine(error);
    }
}

To call it, specify all your params, your working directory, and you're off to the races!!!

        string baseFolder = @"\\Share\folder\";
        string fileNameCash = "Cash.xls";
        string fileNameDV = "DailyValue.xls";
        string fileNameCashOutput = "Cash.xlsx";
        string fileNameDVOutput = "DailyValue.xlsx";
        //Create cash & dailyValue as xlsx files (for ease of use with EPPlus4)
        string pathToExe = @"C:\Program Files (x86)\Microsoft Office\root\Office16\excelcnv.exe";//Path to office XLS to XLSX Conversion Tool for o365 - You can find a similar version by searching for the excelcnv.exe within "C:\Program Files (x86)\Microsoft Office" folder.
        string commandFormat1 = string.Format(@"""{0}"" -oice ""{1}{2}"" ""{3}{4}"" ",pathToExe, @BaseFolder, fileNameCash,@BaseFolder,fileNameCashOutput);
        Xls2XlsxCmdProcess.ExecuteCommandSync(pathToExe, string.Format(commandFormat1));
        

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 Praveen M
Solution 3