博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ajax模拟表单提交,后台使用npoi实现导入操作 方式一
阅读量:5251 次
发布时间:2019-06-14

本文共 11555 字,大约阅读时间需要 38 分钟。

页面代码:

 
View Code

js代码:

//导入excel数据        $("#dataExport").click(function () {            var formData = new FormData($('form')[0]);            $.ajax({                url: '/BaseInfoPage/Upload',                type: 'POST',                xhr: function () {                    return $.ajaxSettings.xhr();                },                data: formData,                cache: false,                contentType: false,                processData: false,                success: function (data) {                    if (data == "导入成功!") {                        layer.msg(data, { icon: 1, time: 5000 }, function () {                            location.reload();    //刷新父页面   第二个参数设置msg显示的时间长短                        });                    } else {                        layer.msg(data, { icon: 0, time: 5000 }, function () {                            return;                        });                    }                },                error: function (e) {                    layer.msg(e, { icon: 0, time: 5000 }, function () {                        return;                    });                }            });        })
View Code

c#后台代码:

public string Upload(HttpPostedFileBase fileUpload)        {            if (fileUpload == null)            {                return "文件为空";            }            string fileExtension = Path.GetExtension(fileUpload.FileName);//获取文件名后缀            try            {                //判断文件类型                if (".xls" == fileExtension || ".xlsx" == fileExtension)                {                    //将硬盘路径转化为服务器路径的文件流                    //string fileName = Path.Combine(Request.MapPath("~/ExcelTemplate"), Path.GetFileName(fileUpload.FileName));                    string fileName = fileUpload.FileName;                    string filePath = "";                    filePath = CSysCfg.exFilePath;                    if (!Directory.Exists(filePath))                    {                        Directory.CreateDirectory(filePath);                    }                    //保存模板到服务器                                fileUpload.SaveAs(filePath + "\\" + fileName);                    //从NPOI读取到的Excel的数据,保存到excelTable里                    DataTable excelTable = new DataTable();                    excelTable = GetExcelDataTable(filePath + "\\" + fileName);//自定义方法                    //把表的中文表头转换成数据库表中对应的英文                    DataTable dbdata = new DataTable();                    dbdata.Columns.Add("ltl_Id");                    dbdata.Columns.Add("ltl_PlateId");                    dbdata.Columns.Add("ltl_StarteTime");                    dbdata.Columns.Add("ltl_EndTime");                                      for (int i = 0; i < excelTable.Rows.Count; i++)                    {                        DataRow dr = excelTable.Rows[i];                        DataRow dr_ = dbdata.NewRow();                        dr_["ltl_Id"] = dr["申请编号"];                        dr_["ltl_PlateId"] = dr["车牌号码"];                        dr_["ltl_StarteTime"] = dr["开始日期"];                        dr_["ltl_EndTime"] = dr["结束日期"];                        dbdata.Rows.Add(dr_);                    }                    RemoveEmpty(dbdata);//自定义方法                    //获取连接字符串,调用批量插入数据库的方法  需更改web.config添加配置                    string constr = System.Configuration.ConfigurationManager.AppSettings["exportData"];                    SqlBulkCopyByDatatable(constr, "LargeTransportLicense", dbdata);//自定义方法(连接字符串,表名,数据)                    return "导入成功!";                }                else                {                    return "只可以选择Excel文件!";                }            }            catch            {                return "导入失败!";            }        }        // 从Excel中获取数据到DataTable           public static DataTable GetExcelDataTable(string filePath)        {            IWorkbook Workbook;            DataTable table = new DataTable();            try            {                using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))                {                    //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;                    }                }                //定位在第一个sheet                ISheet sheet = Workbook.GetSheetAt(0);                //第一行为标题行                IRow headerRow = sheet.GetRow(1);                int cellCount = headerRow.LastCellNum;// 是当前行的总列数                int rowCount = sheet.LastRowNum;////LastRowNum 是当前表的总行数-1(注意)                //循环添加标题列                for (int i = headerRow.FirstCellNum; i < cellCount; i++)                {                    DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);                    table.Columns.Add(column);                }                List
regionName = new List
(); //数据 for (int i = (sheet.FirstRowNum + 2); 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] = GetCellValue2(row.GetCell(j)); } } } table.Rows.Add(dataRow); } } catch (Exception ex) { throw ex; } return table; } //数据类型判断 方式一 private static string GetCellValue(NPOI.SS.UserModel.ICell cell) { if (cell == null) { return string.Empty; } else { 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(); } } } } //数据类型判断,并设置为对应的数据类型 方式二 public static object GetCellValue2(NPOI.SS.UserModel.ICell cell) { object value = null; if (cell == null) { value = 0; } try { if (cell.CellType != CellType.Blank) { switch (cell.CellType) { case CellType.Blank: value = string.Empty; break; case CellType.Numeric: // 日期 if (DateUtil.IsCellDateFormatted(cell)) { value = cell.DateCellValue; } else { // 数值 value = cell.NumericCellValue; } break; case CellType.Boolean: // Boolean type value = cell.BooleanCellValue; break; case CellType.Formula: value = cell.CellFormula; break; default: // String type value = cell.StringCellValue; break; } } else { value = 0; } } catch (Exception) { value = 0; } return value; } ///
/// 大数据插入 /// ///
目标库连接 ///
目标表 ///
来源数据 public static void SqlBulkCopyByDatatable(string connectionString, string TableName, DataTable dtSelect) { using (SqlConnection conn = new SqlConnection(connectionString)) { using (SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction)) { try { sqlbulkcopy.DestinationTableName = TableName; sqlbulkcopy.BatchSize = 20000; sqlbulkcopy.BulkCopyTimeout = 0;//不限时间 for (int i = 0; i < dtSelect.Columns.Count; i++) { sqlbulkcopy.ColumnMappings.Add(dtSelect.Columns[i].ColumnName, dtSelect.Columns[i].ColumnName); } sqlbulkcopy.WriteToServer(dtSelect); } catch (System.Exception ex) { throw ex; } } } } //在导入Excel数据的时候,有时候会有空行,用RemoveEmpty方法去空 protected void RemoveEmpty(DataTable dt) { List
removelist = new List
(); for (int i = 0; i < dt.Rows.Count; i++) { bool IsNull = true; for (int j = 0; j < dt.Columns.Count; j++) { if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim())) { IsNull = false; } } if (IsNull) { removelist.Add(dt.Rows[i]); } } for (int i = 0; i < removelist.Count; i++) { dt.Rows.Remove(removelist[i]); } }
View Code

 注:此方法需在web.config中添加配置

 

转载于:https://www.cnblogs.com/-lile/p/11358359.html

你可能感兴趣的文章
文件操作
查看>>
MFC中无标题栏窗口的移动
查看>>
zabbix报错cannot set resource limit: [13] Permission denied解决方法
查看>>
查看linux系统是运行在物理机还是虚拟机方法
查看>>
汇编语言---编码规则及位运算基础
查看>>
gcd函数两种实现(参考)
查看>>
色彩理论学习-摘自百度百科
查看>>
git简单用法
查看>>
python入门16 递归函数 高阶函数
查看>>
JAVA学习课本内容总结
查看>>
Android之Activity系列总结(三)--Activity的四种启动模式
查看>>
烽火传递
查看>>
2018.06.29 NOIP模拟 旅馆(线段树)
查看>>
2018.07.23 codeforces 438D. The Child and Sequence(线段树)
查看>>
2019.03.09 codeforces833B. The Bakery(线段树优化dp)
查看>>
uestc 一个简单的迷宫问题
查看>>
uestc SOUND OF DESTINY
查看>>
Servlet的HelloWorld
查看>>
『减少重复代码!』
查看>>
h5视频微信禁止全屏 x5-playsinline
查看>>