.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;

}

 

转载于:https://www.cnblogs.com/xiaoyao123/p/11579687.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值