如何使用c#将.xls文件转换为.xlsx文件,而无需安装Microsoft Office

本文关键字:文件 安装 Office Microsoft 何使用 xls 转换 xlsx | 更新日期: 2023-09-27 18:02:51

我需要帮助,在不使用Microsoft Office的情况下使用c#将。xls文件转换为。xlsx。

如何使用c#将.xls文件转换为.xlsx文件,而无需安装Microsoft Office

通过一些编码工作,您可以使用NPOI库读取XLS数据并将其作为XLSX写回。

另一种方法(XLSX到XLS)在c#中使用NPOI将XLSX文件转换为XLS中显示。

使用下面的查询,

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);
        }

我发布了这个答案,我对这个答案印象深刻,直到我看到这个链接,这是更好更简单的方式:

我知道这已经被问过了,但这是我从别人那里借来的…对不起,我不能给信用,因为我不知道如何给我的想法,但在c#中,创建一个进程,将文件从xls复制到xlsx。没有大惊小怪,没有混乱。这是在。net Core 6.0和o365。

最终,您在进程中运行的字符串(也称为命令提示符)应该看起来像这样:

C:'Program Files (x86)'Microsoft Office'root'Office16'excelcnv.exe"声音呼唤"' '文件夹' Cash.xls&quot分享;"' '文件夹' Cash.xlsx&quot分享

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);
    }
}

要调用它,指定所有参数,工作目录,然后就可以开始了!!

        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));