温馨提示×

c# excel表格中的数据怎么提取

c#
小亿
183
2023-07-26 23:41:15
栏目: 编程语言

在C#中,可以使用Excel Interop库或者第三方库如NPOI来提取Excel表格中的数据。

  1. 使用Excel Interop库:
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();
  1. 使用NPOI库:

首先,需要通过NuGet安装NPOI库。

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表格中的数据。你可以根据具体需求来选择合适的方法。

0