Files
U8-Import/NX.ERP.U8.App/ExcelHelper.cs

94 lines
3.3 KiB
C#
Raw Normal View History

2021-01-05 11:11:28 +08:00

using NPOI.SS.UserModel;
2020-12-18 13:51:58 +08:00
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
2021-01-05 11:11:28 +08:00
2020-12-18 13:51:58 +08:00
namespace U8AppMain
{
2020-12-25 11:07:27 +08:00
/// <summary>
///
/// </summary>
public static class ExcelHelper
2020-12-18 13:51:58 +08:00
{
public static DataTable ExcelToDataTable(Stream steam, string sheetName = null, Dictionary<string, string> fieldName = null,
bool isFirstRowColumn = true)
{
DataTable data = new DataTable();
try
{
var workbook = WorkbookFactory.Create(steam);
ISheet sheet;
if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null) sheet = workbook.GetSheetAt(0);
}
else
{
sheet = workbook.GetSheetAt(0);
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
int startRow;
if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue.Trim();
if (fieldName != null)
{
if (fieldName.ContainsKey(cellValue))
{
cellValue = fieldName[cellValue];
}
}
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow = sheet.FirstRowNum;
}
//最后一列的标号
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null       
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
dataRow[j] = row.GetCell(j).ToString().Trim();
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch (Exception ex)
{
throw ex;
}
}
}
}