是否可以在没有 Office Interop 的情况下将多个 .xls 文件附加到单个 Excel 2003 工作表中?

Is it possible to append multiple .xls files into a single Excel 2003 worksheet without Office Interop?

我有一个 ASP.NET Web API 并且需要在未来的版本中实现此功能。具体来说:

有没有办法在不使用指定的 Office 互操作库或任何付费第三方库(非常欢迎免费第三方库)的情况下执行此操作?

NuGet 安装 Spire.XLS:Install-Package Spire.XLS -版本 9.6.7

Spire.XLS 提供了两种将 excel 文件合并到单个 excel 工作表中的方法:

1.使用 CellRange.Copy()

将 excel 与样式合并
static void Main(string[] args)
{
    string outputPath = "‪output.xls";
    List<string> files = new List<string>();
    files.Add(@"File1.xls");
    files.Add(@"File2.xls");
    CombineFiles(files, outputPath);
}
private static void CombineFiles(List<string> files, string outputPath)
{
    Spire.Xls.Workbook resultworkbook = new Spire.Xls.Workbook();
    resultworkbook.Worksheets.Clear();
    Spire.Xls.Worksheet resultworksheet = resultworkbook.Worksheets.Add("worksheet");

    Spire.Xls.Workbook workbook = new Spire.Xls.Workbook();
    for (int i = 0; i < files.Count; i++)
    {
        workbook.LoadFromFile(files[i]);
        Worksheet sheet = workbook.Worksheets[0];
        if (i == 0)
        {
            sheet.AllocatedRange.Copy(resultworksheet.Range[1, 1], true, true);

        }
        else
        {
            sheet.AllocatedRange.Copy(resultworksheet.Range[resultworksheet.LastRow + 1, 1], true, true);
        }
    }


    resultworkbook.SaveToFile(outputPath, ExcelVersion.Version97to2003);
}

参考:

2。使用 DataTable

合并 excel 不带样式
Workbook workbook1 = new Workbook();
//load the first workbook
workbook1.LoadFromFile(FilePath1);
//load the second workbook
Workbook workbook2 = new Workbook();
workbook2.LoadFromFile(FilePath2);
//load the third workbook
Workbook workbook3 = new Workbook();
workbook3.LoadFromFile(FilePath3);

//import the second and third workbook's first worksheet into the first workbook using datatable
Worksheet sheet1 = workbook1.Worksheets[0];
Worksheet sheet2 = workbook2.Worksheets[0];
Worksheet sheet3 = workbook3.Worksheets[0];

DataTable dataTable1 = sheet2.ExportDataTable();
DataTable dataTable2 = sheet3.ExportDataTable();

sheet1.InsertDataTable(dataTable1, false, sheet1.LastRow + 1, 1);
sheet1.InsertDataTable(dataTable2, false, sheet1.LastRow + 1, 1);

workbook1.SaveToFile(OutputPath + "Merged.xls", ExcelVersion.Version97to2003);

参考: