在 C# 中创建 Excel 表格

本指南分享了在 C#** 中创建 Excel 表的详细信息。本文包含设置 IDE 进行开发的详细信息、编程任务列表以及使用 C# 在 Microsoft Excel 中创建 **表的示例代码。您将了解自定义表格并以不同格式保存输出的各种选项。

在 C# 中创建 Excel 表格的步骤

  1. 设置IDE使用Aspose.Cells for .NET创建表
  2. 创建或加载 Excel 文件并访问可用数据的 sheet
  3. 通过提供带有数据的单元格范围来创建列表对象
  4. 将列表对象的TableStyleType设置为TableStyleMedium10
  5. 将所有数字列的总计标志设置为 true
  6. 添加第二列的总计计算
  7. 保存输出

上述步骤描述了在 C# 中创建简单 Excel 表格的过程。通过加载或创建 Excel 文件、访问工作表并添加包含一系列包含数据的单元格的列表对象来开始该过程。使用引用表格的新列表对象来设置 TableStyleType、显示总计和计算类型 Count 的标志。

C# 中的 Microsoft Excel 表格制作代码

using System;
using System.Linq;
using Aspose.Cells;
using Aspose.Cells.Tables;
class Program
{
static void Main(string[] args) // Table creation in C#
{
new License().SetLicense("License.lic");
// Create a workbook.
Workbook wb = new Workbook();
// Optionally call this function if the workbook has no data
CreateSampleData(ref wb);
// Obtain the first sheet
Worksheet sheet = wb.Worksheets[0];
// Add a new list object with 20 rows and 5 columns
ListObject listObject = sheet.ListObjects[sheet.ListObjects.Add("A1", "E20", true)];
// Set table style
listObject.TableStyleType = TableStyleType.TableStyleMedium10;
// Show the flag to display the Total for all numbers
listObject.ShowTotals = true;
// Set the second column calculation type
listObject.ListColumns[1].TotalsCalculation = TotalsCalculation.Count;
// Saving the Excel file
wb.Save("output.xlsx");
Console.WriteLine("Table created successfully");
}
static void CreateSampleData(ref Workbook wb)
{
// Fill workbook with some dummy data
string[] titles = new string[] {"Employee", "Quarter", "Product", "Country","Sale"};
string[] employees = new string[] {"David", "James","Miya" };
string[] products = new string[] { "Chai", "Chang", "Geitost", "Maxilaku" };
string[] countries = new string[] { "Brazil", "China", "France", "Germany", "India", "Italy" };
foreach (var (item, idx) in titles.Select((value, index) => (value, index)))
wb.Worksheets[0].Cells[0, idx].Value = item;
Random random = new Random();
for(int i = 1; i < 20; i++)
{
wb.Worksheets[0].Cells[i, 0].Value = employees[random.Next() % employees.Count()];
wb.Worksheets[0].Cells[i, 1].Value = (random.Next() % 4) + 1;
wb.Worksheets[0].Cells[i, 2].Value = products[random.Next() % products.Count()];
wb.Worksheets[0].Cells[i, 3].Value = countries[random.Next() % countries.Count()];
wb.Worksheets[0].Cells[i, 4].Value = random.Next() % 2000;
}
}
}

此示例代码演示了在 C#* 中创建 *MS Excel 表的过程。 Worksheet 类包含用于添加表的ListObjects 对象。 TableStyleType 具有 MS Excel 支持的所有默认表格样式,您可以在创建表格时使用它们。

本文教我们如何在 C# 中使用高级 Excel 表格。要在 Excel 文件中插入切片器,请参阅有关 如何使用 C# 在 Excel 中插入切片器 的文章。

 简体中文