C# - 将xls文件转换为没有office组件的xlsx

时间:2023-02-10 22:49:42

I have a server that can't have any office installed on it, so I'm using ClosedXML to do some manipulations on excel files. But ClosedXML only works on .xlsx file and I also have xls file to handle. I spend almost a full day searching for a way to convert .xls files to .xlsx files without using any office libraries (since there is no office installed on my designated server...)

我有一台服务器,不能安装任何办公室,所以我使用ClosedXML对excel文件进​​行一些操作。但ClosedXML仅适用于.xlsx文件,我也有xls文件来处理。我花了差不多一整天时间寻找一种方法将.xls文件转换为.xlsx文件而不使用任何办公室库(因为我的指定服务器上没有安装办公室...)

Can someone PLEASE tell me how can I convert these .xls files to .xlsx files ? I can't use Microsoft.Office.Interop because it requires having office installed on the server.

有人可以告诉我如何将这些.xls文件转换为.xlsx文件?我无法使用Microsoft.Office.Interop,因为它需要在服务器上安装Office。

2 个解决方案

#1


4  

For Microsoft.Office.Interop you need to have office installed.

对于Microsoft.Office.Interop,您需要安装办公室。

You could use OleDb to read it(f.e. into a DataTable). Then use a library like EPPlus or OpenXml to write the xlsx file. Both don't need to have office installed.

您可以使用OleDb来读取它(例如,进入DataTable)。然后使用像EPPlus或OpenXml这样的库来编写xlsx文件。两者都不需要安装办公室。

Creating an xlsx file from a DataTable with EPPLus is easy:

使用EPPLus从DataTable创建xlsx文件很简单:

using (ExcelPackage pck = new ExcelPackage(newFile))
{
  ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Name of Worksheet");
  ws.Cells["A1"].LoadFromDataTable(dataTable, true);
  pck.Save();
}

The first link above shows how to get a DataTable from an xls-file.

上面的第一个链接显示了如何从xls文件获取DataTable。

#2


3  

Thanks to @Tim Schmelter. Here is the code I got from the links:

感谢@Tim Schmelter。这是我从链接获得的代码:

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

#1


4  

For Microsoft.Office.Interop you need to have office installed.

对于Microsoft.Office.Interop,您需要安装办公室。

You could use OleDb to read it(f.e. into a DataTable). Then use a library like EPPlus or OpenXml to write the xlsx file. Both don't need to have office installed.

您可以使用OleDb来读取它(例如,进入DataTable)。然后使用像EPPlus或OpenXml这样的库来编写xlsx文件。两者都不需要安装办公室。

Creating an xlsx file from a DataTable with EPPLus is easy:

使用EPPLus从DataTable创建xlsx文件很简单:

using (ExcelPackage pck = new ExcelPackage(newFile))
{
  ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Name of Worksheet");
  ws.Cells["A1"].LoadFromDataTable(dataTable, true);
  pck.Save();
}

The first link above shows how to get a DataTable from an xls-file.

上面的第一个链接显示了如何从xls文件获取DataTable。

#2


3  

Thanks to @Tim Schmelter. Here is the code I got from the links:

感谢@Tim Schmelter。这是我从链接获得的代码:

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