在VS2017中,使用NPOI库用C#创建一个EXCEL,将传入的数据写入,若传入PASS则所在单元格的背景色为绿色,传入FAIL则所在单元格背景色为红色。
时间: 2024-04-12 07:31:02 浏览: 183
要在 VS2017 中使用 NPOI 库创建一个 Excel 文件,并根据传入的数据将单元格的背景色设置为绿色(PASS)或红色(FAIL),可以使用以下代码:
```csharp
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;
public void CreateExcelFile(string filePath, string[,] data)
{
// 创建一个工作簿
IWorkbook workbook = new HSSFWorkbook();
// 创建一个工作表
ISheet sheet = workbook.CreateSheet("Sheet1");
// 遍历传入的数据数组
for (int i = 0; i < data.GetLength(0); i++)
{
IRow row = sheet.CreateRow(i);
for (int j = 0; j < data.GetLength(1); j++)
{
// 创建单元格
ICell cell = row.CreateCell(j);
// 设置单元格的值
cell.SetCellValue(data[i, j]);
// 根据传入的值设置单元格的背景色
if (data[i, j] == "PASS")
{
// 绿色
cell.CellStyle = GetPassCellStyle(workbook);
}
else if (data[i, j] == "FAIL")
{
// 红色
cell.CellStyle = GetFailCellStyle(workbook);
}
}
}
// 将工作簿保存到文件
using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
workbook.Write(fileStream);
}
}
private ICellStyle GetPassCellStyle(IWorkbook workbook)
{
ICellStyle cellStyle = workbook.CreateCellStyle();
cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Green.Index;
cellStyle.FillPattern = FillPattern.SolidForeground;
return cellStyle;
}
private ICellStyle GetFailCellStyle(IWorkbook workbook)
{
ICellStyle cellStyle = workbook.CreateCellStyle();
cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Red.Index;
cellStyle.FillPattern = FillPattern.SolidForeground;
return cellStyle;
}
```
您可以调用 `CreateExcelFile` 方法来创建一个 Excel 文件,并将传入的数据写入单元格。`filePath` 参数用于指定要保存的文件路径,`data` 参数是一个二维数组,包含要写入的数据。
在遍历数据数组时,根据数据值设置单元格的背景色。如果值为 "PASS",则将单元格背景色设置为绿色;如果值为 "FAIL",则将单元格背景色设置为红色。
希望对您有所帮助!
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)