用NOPI将上传的EXCEL,转换得到DataTable,用SqlBulkCopy将数据写入数据库表中,配置添加默认列及值,对应数据库字段写入数据
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用NOPI将上传的EXCEL,转换得到DataTable,用SqlBulkCopy将数据写入数据库表中,配置添加默认列及值,对应数据库字段写入数据相关的知识,希望对你有一定的参考价值。
前台相关:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>上传数据</title> <script src="../../../res/js/jquery.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { //上传按钮对文件格式进行判断 $(‘#Button_up‘).click(function () { var filename = $(‘#FileUpload1‘).val(); if (filename == ‘‘) { alert(‘请上传文件‘); return false; } else { var exec = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename.toLowerCase()) : ‘‘; if (!(exec == "xlsx" || exec == "xls")) { alert(‘文件格式不正确,请上传excel文件!‘); return false; } } return true; }); }); </script> </head> <body> <form id="form1" runat="server"> <div style="height:50px;line-height:50px;text-align:center;"> <asp:FileUpload ID="FileUpload1" runat="server" Height="25px"/> <asp:Button ID="Button_up" runat="server" Text="上 传" OnClick="ButtonUpClick" Height="25px" /> </div> </form> </body> </html>
后台
using System.Data; using System.IO; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using NPOI.HSSF.UserModel; using System.Data.SqlClient; using Maticsoft.DBUtility; /// <summary> /// 将EXCEL文件上传到服务器,并插入数据库 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void ButtonUpClick(object sender, EventArgs e) { int id = ConvertHelper.Cint0(hidId.Text); if (id == 0) { try { #region 后台对文件格式进行校验 var filename = this.FileUpload1.FileName; if (string.IsNullOrEmpty(filename)) { FineUI.Alert.ShowInParent("请选择上传的文件!", FineUI.MessageBoxIcon.Warning); return; } if (!(filename.IndexOf(".xls") > 0 || filename.IndexOf(".xlsx") > 0)) { FineUI.Alert.ShowInParent("文件格式有误,请上传EXCEL文件", FineUI.MessageBoxIcon.Warning); return; } #endregion //上传路径 string path = Server.MapPath("~/") + "WebManage\\BaseTotalWeb\\UploadWeb\\FileTmp\\"; //将文件保存到临时路径下 string timeStamp = System.DateTime.Now.ToString("yyyyMMddHHmmssfff"); string retStr = UpLoadFiles.FileUpload(path, this.FileUpload1, timeStamp); if (retStr.Equals("上传失败")) { FineUI.Alert.ShowInParent("服务忙,请稍后重试", FineUI.MessageBoxIcon.Warning); return; } //获取DataTable DataTable dt = this.ExcelToDataTable(path + timeStamp + this.FileUpload1.FileName, true); //删除该临时文件 DirFileHelper.DeleteFile(path + timeStamp + this.FileUpload1.FileName); if (dt == null) { FineUI.Alert.ShowInParent("无法获取文件内容", FineUI.MessageBoxIcon.Error); return; } //上传订单号 DateTime dtime = System.DateTime.Now; string strno ="up"+ BaseTotalBll.GetInstence().NextCheckCard(dtime); #region 添加相应的列 //添加一列upOrderNum 并赋值 DataColumn dc = new DataColumn("upOrderNum", typeof(string)); dc.DefaultValue = strno; dt.Columns.Add(dc); //添加upMan 上传人 DataColumn dcUpMan = new DataColumn("upMan", typeof(string)); dcUpMan.DefaultValue = OnlineUsersBll.GetInstence().GetOnlineUsersModel().Manager_LoginName;//获取系统当前用户名 dt.Columns.Add(dcUpMan); //添加isOk 是否使用 DataColumn dcisOk = new DataColumn("isOk", typeof(int)); dcisOk.DefaultValue =0; dt.Columns.Add(dcisOk); //添加cardType 卡类型 0 为设定 1 1年卡 2、2年卡 3、3年卡 DataColumn dccardType = new DataColumn("cardType", typeof(int)); dccardType.DefaultValue = 0; dt.Columns.Add(dccardType); //添加isBegin是否激活 DataColumn dcisBegin = new DataColumn("isBegin", typeof(int)); dcisBegin.DefaultValue = 0; dt.Columns.Add(dcisBegin); //添加isDown 是否导出 DataColumn dcisDown = new DataColumn("isDown", typeof(int)); dcisDown.DefaultValue = 0; dt.Columns.Add(dcisDown); //添加isDel 是否删除 DataColumn dcisDel = new DataColumn("isDel",typeof(int)); dcisDel.DefaultValue = 0; dt.Columns.Add(dcisDel); //添加上传人createMan DataColumn dccreateMan = new DataColumn("createMan",typeof(string)); dccreateMan.DefaultValue = OnlineUsersBll.GetInstence().GetOnlineUsersModel().Manager_LoginName; dt.Columns.Add(dccreateMan); #endregion SqlTransaction tran = null; using (SqlConnection conn = new SqlConnection(DbHelperSQL.connectionString)) { conn.Open();//打开链接 using (tran = conn.BeginTransaction()) { using (SqlBulkCopy copy = new SqlBulkCopy(conn, SqlBulkCopyOptions.KeepIdentity, tran)) { copy.BulkCopyTimeout = 60; copy.BatchSize = dt.Rows.Count; copy.DestinationTableName = "SLWIFI.dbo.[T_Base_CardList]"; copy.ColumnMappings.Add("upOrderNum", "upOrderNum"); copy.ColumnMappings.Add("ICCID号", "cardCTCC"); copy.ColumnMappings.Add("接入号码", "cardAccess"); copy.ColumnMappings.Add("upMan", "upMan"); copy.ColumnMappings.Add("isOk", "isOk"); copy.ColumnMappings.Add("cardType", "cardType"); copy.ColumnMappings.Add("isBegin", "isBegin"); copy.ColumnMappings.Add("isDown", "isDown"); copy.ColumnMappings.Add("isDel", "isDel"); copy.ColumnMappings.Add("createMan", "createMan"); copy.WriteToServer(dt); tran.Commit(); copy.Close(); } } conn.Close(); } } catch (Exception ex) { string str = ex.ToString(); FineUI.Alert.ShowInParent("上传失败", FineUI.MessageBoxIcon.Error); return; } FineUI.Alert.ShowInParent("上传成功", FineUI.MessageBoxIcon.Information); return; } } /// <summary> /// 将excel导入到datatable /// </summary> /// <param name="filePath">excel路径</param> /// <param name="isColumnName">第一行是否是列名</param> /// <returns>返回datatable</returns> public DataTable ExcelToDataTable(string filePath, bool isColumnName) { DataTable dataTable = null; FileStream fs = null; DataColumn column = null; DataRow dataRow = null; IWorkbook workbook = null; ISheet sheet = null; IRow row = null; ICell cell = null; int startRow = 0; try { using (fs = File.OpenRead(filePath)) { // 2007版本 if (filePath.IndexOf(".xlsx") > 0) workbook = new XSSFWorkbook(fs); // 2003版本 else if (filePath.IndexOf(".xls") > 0) workbook = new HSSFWorkbook(fs); if (workbook != null) { sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet dataTable = new DataTable(); if (sheet != null) { int rowCount = sheet.LastRowNum;//总行数 if (rowCount > 0) { IRow firstRow = sheet.GetRow(0);//第一行 int cellCount = firstRow.LastCellNum;//列数 //构建datatable的列 if (isColumnName) { startRow = 1;//如果第一行是列名,则从第二行开始读取 for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { cell = firstRow.GetCell(i); if (cell != null) { if (cell.StringCellValue != null) { column = new DataColumn(cell.StringCellValue); dataTable.Columns.Add(column); } } } } else { for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { column = new DataColumn("column" + (i + 1)); dataTable.Columns.Add(column); } } //填充行 for (int i = startRow; i <= rowCount; ++i) { row = sheet.GetRow(i); if (row == null) continue; dataRow = dataTable.NewRow(); for (int j = row.FirstCellNum; j < cellCount; ++j) { cell = row.GetCell(j); if (cell == null) { dataRow[j] = ""; } else { //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,) switch (cell.CellType) { case CellType.Blank: dataRow[j] = ""; break; case CellType.Numeric: short format = cell.CellStyle.DataFormat; //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理 if (format == 14 || format == 31 || format == 57 || format == 58) dataRow[j] = cell.DateCellValue; else dataRow[j] = cell.NumericCellValue; break; case CellType.String: dataRow[j] = cell.StringCellValue; break; } } } dataTable.Rows.Add(dataRow); } } } } } return dataTable; } catch (Exception) { if (fs != null) { fs.Close(); } return null; } }
以上是关于用NOPI将上传的EXCEL,转换得到DataTable,用SqlBulkCopy将数据写入数据库表中,配置添加默认列及值,对应数据库字段写入数据的主要内容,如果未能解决你的问题,请参考以下文章