在VS2017中用C#利用NOPI插件写一个类,包括两个函数,一个函数用来创建含有时间,UDS报文,是否测试通过的excel表格,另外一个函数逐行写入数据
时间: 2024-02-25 15:51:41 浏览: 32
好的,根据你的要求,我来为你编写一个包含两个函数的C#类,使用NOPI插件来创建和写入Excel表格。
首先,需要安装NOPI插件,可以在NuGet包管理器中搜索NPOI,然后安装NPOI和NPOI.OOXML两个包。
接下来是代码实现:
```csharp
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.IO;
public class ExcelWriter
{
private readonly string _filePath;
public ExcelWriter(string filePath)
{
_filePath = filePath;
}
public void CreateExcel(string sheetName)
{
// 创建Excel工作簿
IWorkbook workbook = new XSSFWorkbook();
// 创建Excel表格
ISheet sheet = workbook.CreateSheet(sheetName);
// 创建表头
IRow headerRow = sheet.CreateRow(0);
headerRow.CreateCell(0).SetCellValue("时间");
headerRow.CreateCell(1).SetCellValue("UDS报文");
headerRow.CreateCell(2).SetCellValue("是否测试通过");
// 保存Excel文件
using (FileStream fs = new FileStream(_filePath, FileMode.Create, FileAccess.Write))
{
workbook.Write(fs);
}
}
public void WriteData(string sheetName, DateTime time, string udsMessage, bool isTestPassed)
{
// 打开Excel文件
using (FileStream fs = new FileStream(_filePath, FileMode.Open, FileAccess.ReadWrite))
{
// 读取Excel工作簿
IWorkbook workbook = new XSSFWorkbook(fs);
// 获取指定名称的Excel表格
ISheet sheet = workbook.GetSheet(sheetName);
// 获取下一行行号
int rowCount = sheet.LastRowNum + 1;
// 创建新行
IRow row = sheet.CreateRow(rowCount);
// 在新行中写入数据
row.CreateCell(0).SetCellValue(time.ToString("yyyy-MM-dd HH:mm:ss"));
row.CreateCell(1).SetCellValue(udsMessage);
row.CreateCell(2).SetCellValue(isTestPassed ? "Yes" : "No");
// 保存Excel文件
workbook.Write(fs);
}
}
}
```
这个类有两个函数:CreateExcel和WriteData。CreateExcel函数用于创建表格,包括表头;WriteData函数用于逐行写入数据。可以根据需要多次调用WriteData函数写入多行数据。
使用示例:
```csharp
string filePath = @"D:\test.xlsx";
string sheetName = "Sheet1";
ExcelWriter excelWriter = new ExcelWriter(filePath);
excelWriter.CreateExcel(sheetName);
excelWriter.WriteData(sheetName, DateTime.Now, "UDS message here", true);
```
其中,filePath是Excel文件的路径,sheetName是表格的名称。调用CreateExcel函数创建表格;调用WriteData函数写入数据。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](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)