C# 手动创建 Excel 表格:100 行 100 列及条件颜色填充
要手动创建一个 100 行 100 列的 Excel 表格,并根据条件填充颜色,可以使用 C# 的 Excel 库,如 EPPlus。
首先,你需要在项目中安装 EPPlus 库。可以通过 NuGet 包管理器控制台或 Visual Studio 界面来完成。
安装 EPPlus 库之后,可以按照以下步骤创建 Excel 表格并填充颜色:
- 引用 EPPlus 库:
using OfficeOpenXml;
using OfficeOpenXml.Style;
- 创建一个新的 Excel 文件:
ExcelPackage.LicenseContext = LicenseContext.NonCommercial; // 设置 EPPlus 许可证上下文
using (ExcelPackage excelPackage = new ExcelPackage())
{
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet1");
// 设置表头样式
using (ExcelRange range = worksheet.Cells[1, 1, 1, 100])
{
range.Style.Font.Bold = true;
range.Style.Fill.PatternType = ExcelFillStyle.Solid;
range.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
}
// 设置表格内容
for (int row = 2; row <= 101; row++)
{
for (int col = 1; col <= 100; col++)
{
worksheet.Cells[row, col].Value = "Cell " + row + "-" + col;
// 根据条件填充颜色
if (row % 2 == 0)
{
worksheet.Cells[row, col].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[row, col].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Yellow);
}
}
}
// 保存 Excel 文件
FileInfo excelFile = new FileInfo("path/to/excel/file.xlsx");
excelPackage.SaveAs(excelFile);
}
以上代码创建了一个名为'Sheet1' 的工作表,在第一行设置了表头样式,并在每个单元格中填充了内容。根据条件,偶数行的单元格被填充为黄色。最后,保存 Excel 文件到指定路径。
请注意替换代码中的'path/to/excel/file.xlsx' 为你希望保存文件的实际路径。
希望这可以帮助你创建 Excel 表格并填充颜色。
原文地址: https://www.cveoy.top/t/topic/kr87 著作权归作者所有。请勿转载和采集!