Excel import sql server

//view

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-3.3.1.js"></script>
</head>
<body>
<div>
<form action="/Home/TestExcel" enctype="multipart/form-data" method="post">
<text>选择上传文件</text>
<input name="file" type="file" id="file" />
<input type="submit" name="Upload" value="导入" />
</form>

<the Table>
<thead>
<TR>
<TH> job number </ th>
<TH> Name </ th>
<TH> Sector </ th>
<TH> Date </ th>
<TH> work </ th >
<TH> commuting </ th>
<TH> work </ th>
<TH> commuting </ th>
<TH> commuting </ th>
<TH> late time </ th>
<TH> leaving early </ th >
<TH> absences </ TH>
<TH> total </ TH>
<TH> Remarks </ TH>
</ TR>
</ thead>
<tbody ID = "TB"> </ tbody>
</ Table>
</ div>
<Script>
$ (Document) .ready (function () {
$ .ajax ({
URL: '/Home/ExcelSelect',
dataType: 'json',
type: 'get',
success: function (data) {
$(data).each(function () {
var tr = '<tr>'
+ '<td>' + this.Tnumber + '</td>'
+ '<td>' + this.Tname + '</td>'
+ '<td>' + this.Depter + '</td>'
+ '<td>' + this.Bdate + '</td>'
+ '<td>' + this.Beonduty + '</td>'
+ '<td>' + this.GetoffWork + '</td>'
+ '<td>' + this.BeondutyTwo + '</td>'
+ '<td>' + this.GetoffWorkTwo + '</td>'
+ '<td>' + this.Belate + '</td>'
+ '<td>' + this.Leaver + '</td>'
+ '<td>' + this.Absenceoftime + '</td>'
+ '<td>' + this.Total + '</td>'
+ '<td>' + this.BText + '</td>'
+ '</tr>';
$("#tb").append(tr);
})
}
})
})
</script>
</body>

</html>

// Controller

using Dapper;
using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Mvc;
using static Test.SqlConCty;

namespace Test.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}

// GET: UploadExcel
public ActionResult Excel(string filePath)
{
return View();
}
[HttpPost]
public ActionResult TestExcel(FormCollection form)
{
HttpPostedFileBase file = Request.Files[0];
string path = Server.MapPath("\\Models");
path += "\\" + file.FileName;
file.SaveAs(path);
ImportExcelFile(path);
return View();
}

/// <summary>
/// 根据Excel列类型获取列的值
/// </summary>
/// <param name="cell">Excel列</param>
/// <returns></returns>
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:
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();
}
}
}

/// <summary>
/// Excel导入
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public DataTable ImportExcelFile(string filePath)
{
HSSFWorkbook hssfworkbook;
#region//初始化信息
try
{
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
}
catch (Exception e)
{
throw e;
}
#endregion

ISheet sheet = hssfworkbook.GetSheetAt(3);
DataTable table = new DataTable();
IRow headerRow = sheet.GetRow(0);//第一行为标题行
int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
int rowCount = sheet.LastRowNum - 2;

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 + 4); 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);
}
//批量添加
using (SqlBulkCopy abc = new SqlBulkCopy(SqlConnectionFactory.Connection))
{
abc.BatchSize = table.Rows.Count;
abc.BulkCopyTimeout = 11;
abc.DestinationTableName = "ExcelTable";
for (int i = 0; i < table.Columns.Count; i++)
{
abc.ColumnMappings.Add(table.Columns[i].ColumnName, i);
}
abc.WriteToServer(table);
}
return table;
}

/// <summary>
/// excel显示
/// </summary>
/// <returns></returns>
public string ExcelSelect()
{
using (SqlConnection con = SqlConnectionFactory.Connection)
{
string sql = "select Tnumber, Tname, Depter, Bdate, Beonduty, GetoffWork, BeondutyTwo, GetoffWorkTwo, Belate, Leaver, Absenceoftime, Total, BText from ExcelTable";
var list = con.Query(sql);
return JsonConvert.SerializeObject(list);
}
}
}
}

////////////////////////// Mapping Model

public class TestExcelModel
{
public int TsetId { get; set; }
public string TheDate { get; set; }
public string Tnumber { get; set; }
public string Tname { get; set; }
public string Depter { get; set; }
public string Bdate { get; set; }
public string Beonduty { get; set; }
public string GetoffWork { get; set; }
public string Belate { get; set; }
public string Leaver { get; set; }
public string Absenceoftime { get; set; }
public string Total { get; set; }
}

///////// Dbhelper

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

public class DBhelper
{
//sql连接字符串
//public static string ConnectString = "server=.;database=test_83;uid=sa;pwd=201326";
private static readonly string ConnectString =ConfigurationManager.ConnectionStrings["StrConn"].ConnectionString;
/// <summary>
/// 查询的方法
/// </summary>
/// <param name="sql">要执行的sql语句</param>
/// <param name="paras">sql的参数</param>
/// <returns></returns>
public static DataTable QuerySql(string sql, SqlParameter[] paras = null)
{
using (SqlConnection Conn = new SqlConnection(ConnectString))
{
try
{
SqlCommand cmd = new SqlCommand(sql, Conn);
if (paras! = null) // check whether it is empty is not empty on the plus
{
cmd.Parameters.AddRange(paras);
}
DataTable dt = new DataTable("dt");
SqlDataAdapter adt = new SqlDataAdapter(cmd);
adt.Fill(dt);
return dt;

}
catch (Exception ex)
{
throw ex;
}

}
}
/// <summary>
/// 执行增删改的方法
/// </summary>
/// <param name="sql">需要执行的sql语句</param>
/// <param name="paras">sql参数</param>
/// <returns></returns>
public static int ExcuteSql(string sql, SqlParameter[] paras = null)
{
using (SqlConnection Conn = new SqlConnection(ConnectString))
{
try
{
Conn.Open();
SqlCommand cmd = new SqlCommand(sql, Conn);
if (paras != null)
{
cmd.Parameters.AddRange(paras);
}
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}

}
}
/// <Summary>
/// performing the method of obtaining the total number of
/// </ Summary>
/// <param name = "SQL"> SQL to be executed </ param>
/// <param name = "paras"> sql parameters </ param>
/// <Returns> </ Returns>
public static Object ScalarSql (String SQL, the SqlParameter [] Paras = null)
{
the using (Conn the SqlConnection the SqlConnection new new = (the ConnectString))
{
the try
{
Conn.Open ();
the SqlCommand the SqlCommand cmd = new new (SQL, Conn);
IF (Paras = null!)
{
cmd.Parameters.AddRange (Paras);
}
return cmd.ExecuteScalar (); // get the first row is the ExecuteScalar the method of the first column
}
the catch (Exception EX)
{
the throw EX;
}
}
}
}

 

 

/////////////////HttpClientHelp

using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace Test
{
public class HttpClientHelp
{
/// <summary>
/// 调用WebAP时的通用方法
/// </summary>

/// <summary>
General method when invoked /// WebAP
/// </ Summary>
/// <param name = "to verb"> request type </ param>
/// <param name = "URI"> API request address </ param>
/// <param name = "obj"> parameter may be </ param> empty
/// <Returns> </ Returns>
public static String GetApi (String to verb, URI String, Object obj = null)
{
String JSON = string.Empty;

Task<HttpResponseMessage> task = null;
HttpResponseMessage respose = null;

using (HttpClient client = new HttpClient())
{
//client.BaseAddress = new Uri("http://www.baidu.com/aas");
switch (verb.ToLower())
{
case "get":
task = client.GetAsync(uri);
break;
case "post":
task = client.PostAsJsonAsync(uri, obj);
break;
case "put":
task = client.PutAsJsonAsync(uri, obj);
break;
case "delete":
task = client.DeleteAsync(uri);
break;
default:
break;
}
Console.WriteLine("aaa");
task.Wait();
respose = task.Result;
if (respose.IsSuccessStatusCode)
{
var res = respose.Content.ReadAsStringAsync();
json = res.Result;
}
}
return json;
}

}
}

 

//////////////////////////////SqlConnectionFactory

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace Test
{
public class SqlConCty
{
public class SqlConnectionFactory
{
private static readonly string ConnString =
ConfigurationManager.ConnectionStrings["DapperDemo"].ConnectionString;


private static object _obj = new object();

public static SqlConnection Connection
{
get
{
SqlConnection connection = null;

if (connection == null)
{
lock (_obj)
{
if (connection == null)
{
connection = new SqlConnection(ConnString);
}
}
}
connection.Open();
return connection;
}
}
}
}
}

 

/////////////////////////TableModel

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace Test
{
public class TableModel<T> where T : new()
{
public DataTable JsonToDataTable(string json)
{
DataTable dataTable = new DataTable(); //实例化
DataTable result;
try
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
if (arrayList.Count > 0)
{
foreach (Dictionary<string, object> dictionary in arrayList)
{
if (dictionary.Keys.Count<string>() == 0)
{
result = dataTable;
return result;
}
if (dataTable.Columns.Count == 0)
{
foreach (string current in dictionary.Keys)
{
dataTable.Columns.Add(current, dictionary[current].GetType());
}
}
DataRow dataRow = dataTable.NewRow();
foreach (string current in dictionary.Keys)
{
dataRow[current] = dictionary[current];
}

dataTable.Rows.Add (dataRow); // add rows to the DataTable loop
}
}
}
the catch
{

}
result = dataTable;
return result;
}


}
}

 

 

 

 

///////////////////////////TypeCastHelp

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;

the Test namespace
{
public class TypeCastHelp
{
/// <Summary>
/// entities transformed auxiliary class
/// </ Summary>
public class ModelConvertHelper <T> T WHERE: new new ()
{
public static the IList <T> ConvertToModel (the DataTable dt )
{
// set of definitions
IList <T> ts = new List <T> ();

// Get the type of the model of
the Type type = typeof (T);
String TempName = "";

the foreach (DR in the DataRow dt.Rows)
{
T = T new new T ();
// public properties obtained for this model
PropertyInfo [] = t.GetType the propertys () GetProperties ();.
the foreach (PI in the propertys PropertyInfo)
{
TempName = pi.Name; // check the column contains DataTable

IF (dt.Columns.Contains (TempName))
{
// This attribute determines whether there Setter
IF (pi.CanWrite!) Continue;

object value = dr[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}
}
}
}

 

 

 

////////////////

<connectionStrings>
<add name="StrConn" connectionString="server=10.31.69.27;database=Lianxi;uid=sa;pwd=123456;" providerName="System.Data.SqlClient" />
</connectionStrings>

Guess you like

Origin www.cnblogs.com/nxj1997/p/11761067.html