90 lines
3.3 KiB
C#
90 lines
3.3 KiB
C#
|
|
using NPOI.SS.UserModel;
|
|||
|
|
using System;
|
|||
|
|
using System.Collections.Generic;
|
|||
|
|
using System.Data;
|
|||
|
|
using System.IO;
|
|||
|
|
using System.Linq;
|
|||
|
|
using System.Text;
|
|||
|
|
using System.Threading.Tasks;
|
|||
|
|
|
|||
|
|
namespace U8AppMain
|
|||
|
|
{
|
|||
|
|
public static class ExcelHelper
|
|||
|
|
{
|
|||
|
|
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;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|