我们可以在Excel表格的最下方添加一个汇总行来快速汇总数据。本文将介绍如何使用Spire.XLS给Excel表格添加汇总行。
示例Excel文档如下:
C#
//创建Workbook实例
Workbook workbook = new Workbook();
//加载Excel文件
workbook.LoadFromFile("Input.xlsx");
//获取第一张工作表
Worksheet sheet = workbook.Worksheets[0];
//使用指定的数据范围创建表格
IListObject table = sheet.ListObjects.Create("Table", sheet.Range["A1:D4"]);
//显示汇总行
table.DisplayTotalRow = true;
//添加汇总行
table.Columns[0].TotalsRowLabel = "Total";
table.Columns[1].TotalsCalculation = ExcelTotalsCalculation.Sum;
table.Columns[2].TotalsCalculation = ExcelTotalsCalculation.Sum;
table.Columns[3].TotalsCalculation = ExcelTotalsCalculation.Sum;
//保存文件
workbook.SaveToFile("AddTotalRow.xlsx", ExcelVersion.Version2013);
VB.NET
'创建Workbook实例
Dim workbook As New Workbook()
'加载Excel文件
workbook.LoadFromFile("Input.xlsx")
'获取第一张工作表
Dim sheet As Worksheet = workbook.Worksheets(0)
'使用指定的数据范围创建表格
Dim table As IListObject = sheet.ListObjects.Create("Table", sheet.Range("A1:D4"))
'显示汇总行
table.DisplayTotalRow = True
'添加汇总行
table.Columns(0).TotalsRowLabel = "Total"
table.Columns(1).TotalsCalculation = ExcelTotalsCalculation.Sum
table.Columns(2).TotalsCalculation = ExcelTotalsCalculation.Sum
table.Columns(3).TotalsCalculation = ExcelTotalsCalculation.Sum
'保存文件
workbook.SaveToFile("AddTotalRow.xlsx", ExcelVersion.Version2013)
效果图: