.net excel上传转DateTable

var file1 = Request.HttpContext.Request.Form.Files["file"];

using (Stream fs = file1.OpenReadStream())
{

if (file1.FileName.EndsWith(".xls"))
{
workbook = new HSSFWorkbook(fs);
}
else if (file1.FileName.EndsWith(".xlsx"))
{
workbook = new XSSFWorkbook(fs);
}

Dictionary<string, string> columnsNameDic = new Dictionary<string, string>();
columnsNameDic.Add("ID", "ID");
 DataTable table = ObjectHelper.ExcelToDataTable(workbook, true, columnsNameDic);

}

 

public static DataTable ExcelToDataTable(IWorkbook workbook, bool isFirstRowColumn, Dictionary<string, string> columnsNameDic)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;

sheet = workbook.GetSheetAt(0);

if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue.Trim();
if (cellValue != null)
{
DataColumn column = new DataColumn(columnsNameDic[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       
if (row.GetCell(0).ToString().IsNullOrEmpty()) continue;

DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null)
{

dataRow[j] = row.GetCell(j).ToString();

}

}
data.Rows.Add(dataRow);
}
}

return data;

}

 

posted @ 2019-09-24 17:38  Mr.Alpha  阅读(184)  评论(0编辑  收藏  举报