C# NPOI officedocument.spreadsheetml.sheet
时间: 2024-06-14 14:06:47 浏览: 13
C# NPOI是一个用于读取和写入Excel文件的开源库。它支持使用Open Office Xml格式(xlsx)进行操作。相比于EPPlus,NPOI不需要安装Office Excel,因此更加方便使用。
下面是一个使用C# NPOI读取和写入Excel文件的示例:
1. 首先,你需要在项目中添加NPOI的引用。你可以通过NuGet包管理器来添加NPOI引用。
2. 读取Excel文件:
```csharp
using NPOI.SS.UserModel;using NPOI.XSSF.UserModel;
using System.IO;
// 读取Excel文件
string filePath = "path/to/your/excel/file.xlsx";
FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
IWorkbook workbook = new XSSFWorkbook(file);
ISheet sheet = workbook.GetSheetAt(0);
// 遍历行和列
for (int row = 0; row <= sheet.LastRowNum; row++)
{
IRow currentRow = sheet.GetRow(row);
if (currentRow != null)
{
for (int col = 0; col < currentRow.LastCellNum; col++)
{
ICell cell = currentRow.GetCell(col);
if (cell != null)
{
string cellValue = cell.ToString();
// 处理单元格的值
// ...
}
}
}
}
file.Close();
```
3. 写入Excel文件:
```csharp
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;
// 创建Excel工作簿
IWorkbook workbook = new XSSFWorkbook();
ISheet sheet = workbook.CreateSheet("Sheet1");
// 写入数据
for (int row = 0; row < data.Length; row++)
{
IRow currentRow = sheet.CreateRow(row);
for (int col = 0; col < data[row].Length; col++)
{
ICell cell = currentRow.CreateCell(col);
cell.SetCellValue(data[row][col]);
}
}
// 保存Excel文件
string filePath = "path/to/save/excel/file.xlsx";
FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write);
workbook.Write(file);
file.Close();
```
请注意,上述示例中的"data"是一个二维数组,用于存储要写入Excel文件的数据。