zoukankan      html  css  js  c++  java
  • Excel导入 sql server

    //视图

    @{
    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>

    <table>
    <thead>
    <tr>
    <th>工号</th>
    <th>姓名</th>
    <th>所属部门</th>
    <th>日期</th>
    <th>上班</th>
    <th>下班</th>
    <th>上班</th>
    <th>下班</th>
    <th>下班</th>
    <th>迟到时间</th>
    <th>早退时间</th>
    <th>缺勤时间</th>
    <th>合计</th>
    <th>备注</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>

    //控制器

    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);
    }
    }
    }
    }

    //////////////////////////映射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) //判断参数是否为空 不为空就加上
    {
    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>
    /// 执行获取总条数的方法
    /// </summary>
    /// <param name="sql"> 需要执行的sql</param>
    /// <param name="paras">sql参数</param>
    /// <returns></returns>
    public static object ScalarSql(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.ExecuteScalar(); //ExecuteScalar 是获取首行首列的方法
    }
    catch (Exception ex)
    {
    throw ex;
    }
    }
    }
    }

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

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

    /// <summary>
    /// 调用WebAP时的通用方法
    /// </summary>
    /// <param name="verb">请求类型</param>
    /// <param name="uri">请求API地址</param>
    /// <param name="obj">参数 可以为空</param>
    /// <returns></returns>
    public static string GetApi(string verb, string uri, 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); //循环添加行到DataTable中
    }
    }
    }
    catch
    {

    }
    result = dataTable;
    return result;
    }


    }
    }

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

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

    namespace Test
    {
    public class TypeCastHelp
    {
    /// <summary>
    /// 实体转换辅助类
    /// </summary>
    public class ModelConvertHelper<T> where T : new()
    {
    public static IList<T> ConvertToModel(DataTable dt)
    {
    // 定义集合
    IList<T> ts = new List<T>();

    // 获得此模型的类型
    Type type = typeof(T);
    string tempName = "";

    foreach (DataRow dr in dt.Rows)
    {
    T t = new T();
    // 获得此模型的公共属性
    PropertyInfo[] propertys = t.GetType().GetProperties();
    foreach (PropertyInfo pi in propertys)
    {
    tempName = pi.Name; // 检查DataTable是否包含此列

    if (dt.Columns.Contains(tempName))
    {
    // 判断此属性是否有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>

  • 相关阅读:
    【史上最全】DDoS防御产品服务合集
    DDoS攻击与防御的心得体会
    防范DDoS攻击的15个方法
    什么是DDoS攻击?
    蜜罐技术详解
    全年DDoS攻击分析|知道创宇云安全2018年度网络安全态势报告
    抗D十招:十个方法完美解决DDoS攻击防御难题
    DDOS 攻击的防范教程--转载自阮一峰的博客
    手把手教你查看网站遭受到的Web应用攻击类型
    mlbox ImportError: Cannot load backend 'TkAgg' which requires the 'tk' interactive framework, as 'headless' is currently running
  • 原文地址:https://www.cnblogs.com/nxj1997/p/11761067.html
Copyright © 2011-2022 走看看