一:需要引用NPOI的dll ,可以直接在Nuget上直接下载,步骤如下:
二:引用到 NPOI后,需要前端代码:
这个是cshtml文件里面的全部代码。效果如下图:
注意 js里面有如下一段代码 var data = new FormData(document.forms[0]); 是获取文件的流
@{
ViewBag.Title = "导入加盟信息";
}
三:控制器代码:
注意:1:string serverpath = Server.MapPath(string.Format("~/{0}", "Upload\\Franchisee\\"));里面的Upload\\Franchisee\\文件夹需要手动创建
2: HttpPostedFileBase mypost = Request.Files[0]; 是读取excel的路径
3: mypost.SaveAs(path); 把excel文件导入到了站点根目录下
4:GetExcelDataTable 读取excel的方法,具体详细看四的代码
public JsonResult ProviderCatalogUpload(HttpPostedFileBase file)
{
DataTable excelTable = new DataTable();
string msg = string.Empty;
bool b = false;
if (Request.Files.Count > 0)
{
try
{
HttpPostedFileBase mypost = Request.Files[0];
string fileName = Request.Files[0].FileName;
string serverpath = Server.MapPath(string.Format("~/{0}", "Upload\\Franchisee\\"));
string path = Path.Combine(serverpath, fileName);
mypost.SaveAs(path);
excelTable = ImportExcel.GetExcelDataTable(path);
//注意Excel表内容格式,第一行必须为列名与数据库列名匹配
//接下来为各列名对应下来的内容
msg = SaveExcelToDB.InsertDataToDB(excelTable, "Table");// 写入基础数据
if (msg == "导入成功")
{
b = true;
}
}
catch (Exception ex)
{
msg = ex.Message;
}
}
else
{
msg = "请选择文件";
}
return Json(new { result = b, message = msg });
}
四:读取EXCEL内容
注意:1:Workbook 读取的数据,日期 是有格式问题,一般格式是 28-4月-2020 这样的格式。所以 需要做一个转换功能。
transferInvalidDateFormat这个方法就是转换用的
2:日期类型在workbook里面是Numeric类型的,所以读取日期的时候回出现问题
3:日期转换的方法需要注意,具体性格具体处理,并且需要根据excel的日期设置的什么格式确认
4:在web站点的项目里面需要引用到 NPOT的引用
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
namespace GTOW.WebManager.Common
{
public static class ImportExcel
{
public static DataTable GetExcelDataTable(string filePath)
{
IWorkbook Workbook;
DataTable table = new DataTable();
try
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
//XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
string fileExt = Path.GetExtension(filePath).ToLower();
if (fileExt == ".xls")
{
Workbook = new HSSFWorkbook(fileStream);
}
else if (fileExt == ".xlsx")
{
Workbook = new XSSFWorkbook(fileStream);
}
else
{
Workbook = null;
}
}
}
catch (Exception ex)
{
throw ex;
}
//定位在第一个sheet
ISheet sheet = Workbook.GetSheetAt(0);
//第一行为标题行
IRow headerRow = sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
int rowCount = sheet.LastRowNum;
//循环添加标题列
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
}
//数据
for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = table.NewRow();
if (row != null)
{
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
{
dataRow[j] = GetCellValue(row.GetCell(j));
}
}
}
table.Rows.Add(dataRow);
}
return table;
}
private static string GetCellValue(ICell cell)
{
if (cell == null)
{
return string.Empty;
}
switch (cell.CellType)
{
case CellType.Blank:
return string.Empty;
case CellType.Boolean:
return cell.BooleanCellValue.ToString();
case CellType.Error:
return cell.ErrorCellValue.ToString();
case CellType.Numeric:
{
String dateValue = cell.ToString();
if (cell.ToString().Contains("月"))
{
dateValue = transferInvalidDateFormat(cell.ToString());
}
return dateValue;
}
case CellType.Unknown:
default:
return cell.ToString();
case CellType.String:
return cell.StringCellValue;
case CellType.Formula:
try
{
HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
e.EvaluateInCell(cell);
return cell.ToString();
}
catch
{
return cell.NumericCellValue.ToString();
}
}
}
/** * 转换非法的日期格式到指定的日期格式(转化为String) * @param cell excel单元格(值类型为数字) * @return 转化后的日期字符串 */
public static String transferInvalidDateFormat(string cell)
{ /** * 读取cell的日期值,一般为:01-七月-1996等 */
String cellValue = cell.ToString();
//获取天
String day = cellValue.Substring(0, 2);
//获取月(这里使用cellValue.length() - 5是因为可能出现"七月"和"十一月"长度不一致的情况)
String month = cellValue.Substring(3, cellValue.Length - 8);
//获取年
String year = cellValue.Substring(cellValue.Length - 4, 4);
//把中文的月份转化为数字
switch (month) {
case "1月":
month = "01";
break;
case "2月":
month = "02";
break;
case "3月":
month = "03";
break;
case "4月":
month = "04";
break;
case "5月":
month = "05";
break;
case "6月":
month = "06";
break;
case "7月":
month = "07";
break;
case "8月":
month = "08";
break;
case "9月":
month = "09";
break;
case "10月":
month = "10";
break;
case "11":
month = "11";
break;
case "12":
month = "12";
break;
default:
break;
}
//按照"yyyy.mm.dd的格式拼接"
StringBuilder sb = new StringBuilder();
return sb.Append(year).Append("-").Append(month).Append("-").Append(day).ToString();
}
}
}
五:保存数据到数据库
注意:这里用的是批量插入的方法 SqlBulkCopy 需要注意SqlBulkCopy插入数据库的规则,
1:表名跟数据库名一致
2:表字段跟数据库字段一致
3:表字段类型 跟数据库字段类型一致
4:表的字段顺序跟数据库字段顺序一致
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
namespace GTOW.WebManager.DAL.DAL
{
public static class SaveExcelToDB
{
//数据库连接字符串(web.config来配置)
private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["GTOWConnect"].ConnectionString;
///
/// 把excel里面读取的数据导入到GTOW表中
///
///
///
///
public static string InsertDataToDB(DataTable dt, string TableName)
{
string Result = string.Empty;
if (dt == null || dt.Rows.Count == 0)
{
Result= "Excel无内容";
}
if (dt.Columns.Count < 6)
{
Result= "Excel模板列数量不正确";
}
bool isColumn = true;
if (!dt.Columns.Contains("咨询日期") || !dt.Columns.Contains("姓名") || !dt.Columns.Contains("联系方式") || !dt.Columns.Contains("地区") || !dt.Columns.Contains("信息获取渠道") || !dt.Columns.Contains("备注"))
{
isColumn = false;
}
if (!isColumn)
{
Result= "Excel模板列名称不正确";
}
// 校验Excel数据正确性 1:列数一致 2:列名相同 3:保存到新的datatable中 4:批量插入到表中
// 校验数据正确性 手机号码不能为空
for (int row = 0; row < dt.Rows.Count; row++)
{
DataRow record = dt.Rows[row];
foreach (DataColumn c in dt.Columns)
{
if (c.ColumnName == "联系方式")
{
if (string.IsNullOrEmpty(record["联系方式"].ToString().Trim()))
{
Result += string.Format("第{0}数据联系方式不能为空", row) + ";";
}
}
}
}
// 创建需要新增的表
DataTable JoinDt = new DataTable("JoinGreenTreeInn");
JoinDt.Columns.Add(new DataColumn("ID", typeof(Int64)));
JoinDt.Columns.Add(new DataColumn("soueceCode", typeof(String)));
JoinDt.Columns.Add(new DataColumn("SourceType", typeof(int)));
JoinDt.Columns.Add(new DataColumn("FranchiseeName", typeof(String)));
JoinDt.Columns.Add(new DataColumn("Contact", typeof(String)));
JoinDt.Columns.Add(new DataColumn("HotelAdderssCity", typeof(String)));
JoinDt.Columns.Add(new DataColumn("ConstructionArea", typeof(decimal)));
JoinDt.Columns.Add(new DataColumn("LeaveMessage", typeof(String)));
JoinDt.Columns.Add(new DataColumn("PropertyAddress", typeof(String)));
JoinDt.Columns.Add(new DataColumn("PropertyRights", typeof(int)));
JoinDt.Columns.Add(new DataColumn("CooperationIntention", typeof(int)));
JoinDt.Columns.Add(new DataColumn("Remark", typeof(String)));
JoinDt.Columns.Add(new DataColumn("State", typeof(int)));
JoinDt.Columns.Add(new DataColumn("CreateTime", typeof(DateTime)));
JoinDt.Columns.Add(new DataColumn("Distribute", typeof(int)));
foreach (DataRow row in dt.Rows)
{
DataRow dr = JoinDt.NewRow();
dr["soueceCode"] = row["信息获取渠道"].ToString();
dr["SourceType"] = 4;
dr["FranchiseeName"] = row["姓名"].ToString();
dr["Contact"] = row["联系方式"].ToString();
dr["HotelAdderssCity"] = row["地区"].ToString();
dr["LeaveMessage"] = row["备注"].ToString();
dr["PropertyRights"] = 0;
dr["CooperationIntention"] = 0;
dr["State"] = 0;
dr["CreateTime"] = Convert.ToDateTime(row["咨询日期"].ToString());
dr["Distribute"] =0;
JoinDt.Rows.Add(dr);
}
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(ConnectionString))
{
bulkCopy.ColumnMappings.Add("ID", "ID");
bulkCopy.ColumnMappings.Add("soueceCode", "soueceCode");
bulkCopy.ColumnMappings.Add("SourceType", "SourceType");
bulkCopy.ColumnMappings.Add("FranchiseeName", "FranchiseeName");
bulkCopy.ColumnMappings.Add("Contact", "Contact");
bulkCopy.ColumnMappings.Add("HotelAdderssCity", "HotelAdderssCity");
bulkCopy.ColumnMappings.Add("ConstructionArea", "ConstructionArea");
bulkCopy.ColumnMappings.Add("LeaveMessage", "LeaveMessage");
bulkCopy.ColumnMappings.Add("PropertyAddress", "PropertyAddress");
bulkCopy.ColumnMappings.Add("PropertyRights", "PropertyRights");
bulkCopy.ColumnMappings.Add("CooperationIntention", "CooperationIntention");
bulkCopy.ColumnMappings.Add("Remark", "Remark");
bulkCopy.ColumnMappings.Add("State", "State");
bulkCopy.ColumnMappings.Add("CreateTime", "CreateTime");
bulkCopy.ColumnMappings.Add("Distribute", "Distribute");
bulkCopy.DestinationTableName = "Join_GreenTreeInn";
bulkCopy.BulkCopyTimeout = 600;
bulkCopy.BatchSize = 10000;
bulkCopy.WriteToServer(JoinDt);
Result = "导入成功";
}
return Result;
}
}
}