NPOI excel读取转datatabel excel日期格式处理
/// <summary> /// 将excel中的数据导入到DataTable中 /// </summary> /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param> /// <returns>返回的DataTable</returns> public DataTable ExcelToDataTable(bool isFirstRowColumn) { ISheet sheet = null; IWorkbook workbook = null; DataTable data = new DataTable(); int startRow = 0; try { if (fileupload2.FileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(fileupload2.PostedFile.InputStream); else if (fileupload2.FileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(fileupload2.PostedFile.InputStream); sheet = workbook.GetSheetAt(0); if (sheet != null) { IRow firstRow = sheet.GetRow(0); int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数 if (isFirstRowColumn) { for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { ICell cell = firstRow.GetCell(i); if (cell != null) { string cellValue = cell.StringCellValue; if (!string.IsNullOrEmpty(cellValue)) { DataColumn column = new DataColumn(cellValue); data.Columns.Add(column); } } } startRow = sheet.FirstRowNum + 1; } else { startRow = sheet.FirstRowNum; } //最后一列的标号 int rowCount = sheet.LastRowNum; for (int i = startRow; i <= rowCount; ++i) { IRow row = sheet.GetRow(i); if (row == null) continue; //没有数据的行默认是null DataRow dataRow = data.NewRow(); for (int j = row.FirstCellNum; j < cellCount; ++j) { if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null dataRow[j] = row.GetCell(j).ToString(); if (row.GetCell(j) != null&&row.GetCell(j).CellType == CellType.Numeric) { //NPOI中数字和日期都是NUMERIC类型的,这里对其进行判断是否是日期类型 if (HSSFDateUtil.IsCellDateFormatted(row.GetCell(j)))//日期类型 { dataRow[j] = row.GetCell(j).DateCellValue; } } } data.Rows.Add(dataRow); } } return data; } catch (Exception ex) { LogNet.info("Exception: " + ex.ToString()); return null; } }
批量插入
//使用SqlBulkCopy将DataTable中的数据批量插入数据库中 /// <summary> /// 注意:DataTable中的列需要与数据库表中的列完全一致。 /// 已自测可用。 /// </summary> /// <param name="conStr">数据库连接串</param> /// <param name="strTableName">数据库中对应的表名</param> /// <param name="dtData">数据集</param> public static void SqlBulkCopyInsert(string conStr, string strTableName, DataTable dtData) { try { using (SqlBulkCopy sqlRevdBulkCopy = new SqlBulkCopy(conStr))//引用SqlBulkCopy { sqlRevdBulkCopy.DestinationTableName = strTableName;//数据库中对应的表名 sqlRevdBulkCopy.NotifyAfter = dtData.Rows.Count;//有几行数据 sqlRevdBulkCopy.ColumnMappings.Add("id", "id"); sqlRevdBulkCopy.ColumnMappings.Add("pay_no", "pay_no"); sqlRevdBulkCopy.ColumnMappings.Add("pay_money", "pay_money"); sqlRevdBulkCopy.ColumnMappings.Add("pay_time", "pay_time"); sqlRevdBulkCopy.WriteToServer(dtData);//数据导入数据库 sqlRevdBulkCopy.Close();//关闭连接 } } catch (Exception ex) { LogNet.info(ex.ToString()); } }