承接国内外服务器租用托管、定制开发、网站代运营、网站seo优化托管接单、网站代更新,新老站点皆可!!咨询QQ:3787320601

c# excel表格中的数据如何提取

管理员 2023-09-22 09:33:50 网站建设 0 ℃ 0 评论 2398字 收藏

c# excel表格中的数据如何提取

c# excel表格中的数据如何提取

在C#中,可使用Excel Interop库还是第三方库如NPOI来提取Excel表格中的数据。
1. 使用Excel Interop库:
```csharp
using Excel = Microsoft.Office.Interop.Excel;
// 打开Excel文件
Excel.Application excelApp = new Excel.Application();
Excel.Workbook workbook = excelApp.Workbooks.Open(@"C:\path\to\your\excel.xlsx");
Excel.Worksheet worksheet = workbook.Sheets[1];
// 获得数据范围
Excel.Range range = worksheet.UsedRange;
// 遍历每一个单元格并提取数据
for (int row = 1; row <= range.Rows.Count; row++)
{
for (int column = 1; column <= range.Columns.Count; column++)
{
// 获得单元格的值
string cellValue = range.Cells[row, column].Value.ToString();
Console.WriteLine(cellValue);
}
}
// 关闭Excel利用程序
workbook.Close();
excelApp.Quit();
```
2. 使用NPOI库:
首先,需要通过NuGet安装NPOI库。
```csharp
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
// 打开Excel文件
FileStream fs = new FileStream(@"C:\path\to\your\excel.xlsx", FileMode.Open, FileAccess.Read);
IWorkbook workbook = new XSSFWorkbook(fs);
ISheet sheet = workbook.GetSheetAt(0);
// 获得数据行数
int rowCount = sheet.LastRowNum + 1;
// 遍历每行并提取数据
for (int row = 0; row < rowCount; row++)
{
IRow excelRow = sheet.GetRow(row);
// 获得每行中的单元格数量
int cellCount = excelRow.LastCellNum;
// 遍历每一个单元格并提取数据
for (int cell = 0; cell < cellCount; cell++)
{
ICell excelCell = excelRow.GetCell(cell);
// 根据单元格类型提取数据
string cellValue = "";
if (excelCell.CellType == CellType.Numeric)
{
cellValue = excelCell.NumericCellValue.ToString();
}
else if (excelCell.CellType == CellType.String)
{
cellValue = excelCell.StringCellValue;
}
else if (excelCell.CellType == CellType.Boolean)
{
cellValue = excelCell.BooleanCellValue.ToString();
}
Console.WriteLine(cellValue);
}
}
// 关闭文件流
fs.Close();
```
以上代码示例提供了两种方法来提取Excel表格中的数据。你可以根据具体需求来选择适合的方法。

文章来源:丸子建站

文章标题:c# excel表格中的数据如何提取

https://www.wanzijz.com/view/89073.html

TAG: c# excel c#

相关文章

Related articles

X

截屏,微信识别二维码

微信号:weimawl

(点击微信号复制,添加好友)

打开微信