我有一个ASP.NET Web API,需要在以后的版本中实现此功能。具体来说:
是否有一种方法可以不使用指定的Office互操作库或任何付费的第三方库(欢迎使用免费的第三方库)?
答案 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#