使用NPOI实现从Excel读入数据到DataTable(C#)
需要注意:当需要在表单内上传文件时(二进制流数据)时,就需要使用multipart/form-data 编码方式。
excel的时间设置为常规就会转为数字,数字与1900年1月1日计算差值
| 日期1 | 常规1 | 日期2 | 常规2 |
| 2018/10/12 | 43385 | 1900/1/1 | 1 |
DateTime.FromOADate(numericValue).ToString("yyyy/MM/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);
.cshtml
<table>
<tr>
<td>Excel读入</td>
<td style="margin-left:20px;" nowrap>
<form id="form1" method="post" enctype="multipart/form-data" action="/Test/TestExcelRead">
<input type="file" name="fileExcel" id="fileExcel" style="width:500px;" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" size="50" />
<input type="submit" style="width:100px;" value="读入" />
</form>
</td>
</tr>
</table>
C#
TestController.java
/// <summary>
/// Excel读入
/// </summary>
/// <returns></returns>
public ActionResult TestExcelRead(TestExcelModel model)
{
HttpFileCollection _file = System.Web.HttpContext.Current.Request.Files;
DataTable dt = null;
if (_file.Count == 0)
{
//错误处理
}
else
{
long size = _file[0].ContentLength; //文件大小
string type = _file[0].ContentType; //文件类型
string name = _file[0].FileName; //文件名
string _tp = Path.GetExtension(name);//文件扩展名
Stream stream = _file[0].InputStream;
string fileName = "";
string sheetName = "";
if (_tp.ToLower() != ".xls" && _tp.ToLower() != ".xlsx")
{
//错误处理
}
else
{
try
{
//必须列
List<string> mustColumns = new List<string>();
mustColumns.Add("COLUMN_NAME_1");
mustColumns.Add("COLUMN_NAME_2");
mustColumns.Add("COLUMN_NAME_3");
//必须列是否有的字典
Dictionary<string, bool> mustColumnDic;
//日期类型的列
List<string> dateCellNameList = new List<string>();
dateCellNameList.Add("COLUMN_NAME_3");
dateCellNameList.Add("COLUMN_NAME_4");
dt = ExcelReadUtil.ReadExcelToDataTable(mustColumns, out mustColumnDic, dateCellNameList, stream, fileName, sheetName, true);
if (mustColumnDic.ContainsValue(false))
{
//错误处理
}
}
catch
{
//错误处理
}
}
}
if (dt != null && dt.Rows.Count > 0)
{
List<string> errorList;
var dataList = AnalyzeExcelData(dt,out errorList);
model.DataList = dataList;
if (errorList.Count > 0)
{
//错误处理
}
else
{
if (dataList.Count == 0)
{
//关联处理
}
else
{
//关联处理
}
}
}
return View(model);
}
TestController .java
/// <summary>
/// 数据读入
/// </summary>
/// <param name="dt"></param>
/// <param name="categoryList"></param>
/// <param name="errorList"></param>
/// <returns></returns>
private List<DataInfo> AnalyzeExcelData(DataTable dt, out List<string> errorList)
{
var dataInfoList = new List<DataInfo>();
errorList = new List<string>();
bool errorFlag = false;
Dictionary<string, bool> columnHasDic = new Dictionary<string, bool>();
columnHasDic.Add("COLUMN_NAME_1", false);
columnHasDic.Add("COLUMN_NAME_2", false);
columnHasDic.Add("COLUMN_NAME_3", false);
columnHasDic.Add("COLUMN_NAME_4", false);
foreach (DataColumn item in dt.Columns)
{
if (columnHasDic.ContainsKey(item.ColumnName))
{
columnHasDic[item.ColumnName] = true;
}
}
foreach (DataRow items in dt.Rows)
{
string column1= string.Empty;
string column2= string.Empty;
string column3= string.Empty;
string column4= string.Empty;
//COLUMN_NAME_1
if (columnHasDic["COLUMN_NAME_1"])
{
categoryName = items.Field<string>("COLUMN_NAME_1");
}
//COLUMN_NAME_2
if (columnHasDic["COLUMN_NAME_2"])
{
categoryName = items.Field<string>("COLUMN_NAME_2");
}
//COLUMN_NAME_3
if (columnHasDic["COLUMN_NAME_3"])
{
categoryName = items.Field<string>("COLUMN_NAME_3");
}
//COLUMN_NAME_4
if (columnHasDic["COLUMN_NAME_4"])
{
categoryName = items.Field<string>("COLUMN_NAME_4");
}
////全部为空判断
if (string.IsNullOrWhiteSpace(column1)
&& string.IsNullOrWhiteSpace(column2)
&& string.IsNullOrWhiteSpace(column3)
&& string.IsNullOrWhiteSpace(column4)
)
{
continue;
}
//各字段check
if (errorList.Count > 0)
{
errorFlag = true;
dataInfoList.Clear();
}
if (!errorFlag)
{
var dataInfo = new DataInfo();
dataInfoList.Add(c);
}
}
return dataInfoList;
}
Excel 读入工具类
ExcelWriteUtil.java
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
namespace Test.Utils
{
public class ExcelWriteUtil
{
/// <summary>
/// 从excel 把数据内容读取到DataTable中
/// </summary>
/// <param name="mustColumnList">必须的项目列表</param>
/// <param name="mustColumnDict">out 必須项目列表状況的字典</param>
/// <param name="dateCellNames">日期项目列表</param>
/// <param name="stream">数据流</param>
/// <param name="fileName">文件路径</param>
/// <param name="sheetName">指定的sheet名</param>
/// <param name="isFirstRowColumn">第一行是不是DataTable列名:true=是,false=否</param>
/// <returns>DataTable数据表</returns>
public static DataTable ReadExcelToDataTable(List<string> mustColumnList, out Dictionary<string, bool> mustColumnDict, List<string> dateCellNames, Stream stream, string fileName, string sheetName = null, bool isFirstRowColumn = true)
{
mustColumnDict = new Dictionary<string, bool>();
foreach (var item in mustColumnList)
{
mustColumnDict.Add(item, false);
}
DataTable data = new DataTable();
ISheet sheet = null;
//数据开始行(标题行除外)
int startRow = 0;
try
{
if ((stream == Stream.Null || stream == null) && !File.Exists(fileName))
{
return null;
}
IWorkbook workbook = null;
if (stream != null && stream != Stream.Null)
{
//创建工作簿
workbook = WorkbookFactory.Create(stream);
}
else if (File.Exists(fileName))
{
//读入指定文件
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
//创建工作簿
workbook = WorkbookFactory.Create(fs);
}
if (string.IsNullOrEmpty(sheetName))
{
//没有指定sheet时,获取第一个sheet
sheet = workbook.GetSheetAt(0);
}
else
{
sheet = workbook.GetSheet(sheetName);
//指定sheet没有找到时,获取第一个sheet
if (sheet == null)
{
sheet = workbook.GetSheetAt(0);
}
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum;
if (isFirstRowColumn)
{
int mustColumnCount = 0;
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
if (mustColumns.Contains(cellValue))
{
mustColumnCount = mustColumnCount + 1;
mustColumnDict[cellValue] = true;
}
}
}
}
if (mustColumnDict.Count != mustColumnCount)
{
return data;
}
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;
}
newDataRow newDataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null)
{
if (dateCellNames != null && dateCellNames.Contains(data.Columns[j].ColumnName))
{
try
{
if (row.GetCell(j).CellType == CellType.Numeric)
{
var numericValue = row.GetCell(j).NumericCellValue;
newDataRow[j] = DateTime.FromOADate(numericValue).ToString("yyyy/MM/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);
}
else if (row.GetCell(j).CellType == CellType.String)
{
newDataRow[j] = row.GetCell(j).ToString();
}
else
{
DateTime dateTime = Convert.ToDateTime(row.GetCell(j).DateCellValue);
if (DateTime.MinValue.CompareTo(dateTime) == 0)
{
newDataRow[j] = null;
}
else
{
newDataRow[j] = dateTime.ToString();
}
}
}
catch
{
try
{
newDataRow[j] = row.GetCell(j).ToString();
}
catch
{
//
}
}
}
else
{
newDataRow[j] = row.GetCell(j).ToString();
}
}
}
data.Rows.Add(newDataRow);
}
}
return data;
}
catch (Exception e)
{
throw e;
}
}
}
}
本文介绍如何使用NPOI库在C#中将Excel文件的数据读取到DataTable,并展示了完整的代码示例,包括处理日期格式及文件上传。

807

被折叠的 条评论
为什么被折叠?



