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

时间:2019-06-21 15:03:32

标签: c# asp.net excel merge excel-2003

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

  • 几个.xls文件将放置在一个临时文件夹中。它们的宽度相同,但高度不同,行和列的大小也不同。
  • 文件需要附加到一个.xls文件中
  • 最终的excel不能有多个工作表。
  • 不能使用Office Interop库,因为尚未安装Office,也无法将其安装在部署环境中。

是否有一种方法可以不使用指定的Office互操作库或任何付费的第三方库(欢迎使用免费的第三方库)?

1 个答案:

答案 0 :(得分:0)

NuGet安装Spire.XLS:安装软件包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);
}

参考:How to merge multiple worksheets to a single worksheet with styles

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

参考:How to merge 3 Sheets from different Excel files into one sheet with C#