使用NPOI导入Excel注意日期格式和数字格式
2015-06-05 14:46
423 查看
//使用NPOI导入Excel public static DataTable importExcelToDataSetUsingNPOI(string FilePath, string fileName) { DataSet myDs = new DataSet(); DataTable dt = new DataTable("mytable"); myDs.Tables.Add(dt); DataRow myRow; myDs.Clear(); try { using (Stream stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read)) { HSSFWorkbook wk = new HSSFWorkbook(stream); ISheet sheet = wk.GetSheetAt(0); //读取当前表数据 只读取第一个sheet int rowsint = sheet.LastRowNum; for (int y = 0; y <= rowsint; y++) { //Execel第一行是标题,不是要导入数据库的数据 IRow row = sheet.GetRow(y); //读取当前行数据 if (row != null) { int columnsint = row.LastCellNum; if (y == 0)//第一行,标题 { for (int m = 0; m < columnsint; m++) { dt.Columns.Add("F" + m.ToString(), System.Type.GetType("System.String")); } } else { myRow = myDs.Tables["mytable"].NewRow(); for (int j = 0; j < columnsint; j++) { if (j == 11) { } if (row.GetCell(j).CellType == CellType.NUMERIC)//数字类型 { string columnname = "F" + j.ToString(); if (DateUtil.IsValidExcelDate(row.GetCell(j).NumericCellValue) && DateUtil.IsCellDateFormatted(row.GetCell(j))) { DateTime D = row.GetCell(j).DateCellValue; myRow[columnname] = (D.ToString().Length == 0 || D.ToString().Contains("#")) ? " " : D.ToString(); } else { double strValue = row.GetCell(j).NumericCellValue; myRow[columnname] = (strValue.ToString().Length == 0 || strValue.ToString().Contains("#")) ? " " : strValue.ToString(); } } else { string strValue = row.GetCell(j).StringCellValue; string columnname = "F" + j.ToString(); myRow[columnname] = (strValue.Length == 0 || strValue.Contains("#")) ? " " : strValue; } } try { myDs.Tables["mytable"].Rows.Add(myRow); } catch { } } } } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } return myDs.Tables["mytable"]; }
相关文章推荐
- spark OutOfMemoryError (GC overhead limit exceeded)
- Win Server 2008 R2主域控灾难恢复
- 【leetcode】Linked List Cycle II
- MongoDB assertion: 18 { code: 18, ok: 0.0, errmsg: "auth fails" }
- MongoDB assertion: 18 { code: 18, ok: 0.0, errmsg: "auth fails" }
- appium简明教程(10)——控件定位基础
- Linux中THIS_MODULE宏定义详解
- ZH奶酪:【数据结构与算法】并查集基础
- python标准库 - socket
- 笔试题:写一个有序整数数组两两之和等于某个数所有组合
- ABAP 弹出框 函数
- AspNet MVC4 教学-26:Asp.Net MVC4 原生态Sql技术快速应用Demo
- 中国气象网 气象数据开放平台 API使用方法 (Android)
- 使用Nginx+FFMPEG搭建HLS直播转码服务器
- appium简明教程(9)——如何获取android app的Activity
- [oc学习日记]单例模式
- 室内地图商场停车场室内定位导航拓展方案应用
- 判断滚轮滚动方向
- ionic使用记录----列表.list
- 批量Load到HBase