NPOI导入xls,xlsx格式实例
NPOI DLL下载地:http://npoi.codeplex.com/releases
using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Topevery.DUM.PublicServer.Manager { public partial class ToiletListImport : BasePage { private static readonly string SavePath = System.Configuration.ConfigurationSettings.AppSettings["SavePath"]; private int _editId; public int EditId { get { _editId = ); return _editId; } set { _editId = value; } } protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { //SetCondition(); } } protected void btnImport_Click(object o, EventArgs e) { // string Msg = ""; ; ; //保存文件 string filePath = string.Format("~/{0}", SavePath); filePath = Path.Combine(filePath, string.Format("{0}_{1}", UserObject.UserID.ToString(), fulOffLineData.FileName)); string strPhysicalPath = Server.MapPath(filePath); fulOffLineData.PostedFile.SaveAs(strPhysicalPath); { IWorkbook workBook = null; ISheet sheet = null; IRow row = null; try { //加载文档 using (FileStream fileStream = new FileStream(strPhysicalPath, FileMode.Open)) { //不同格式实例化不同工作薄 if (strPhysicalPath.EndsWith(".xls"))//2003版本及以上 { workBook = new HSSFWorkbook(fileStream); } else if (strPhysicalPath.EndsWith(".xlsx"))//2007版本及以上 { workBook = new XSSFWorkbook(fileStream); } } //加载指定工作薄 sheet = workBook.GetSheetAt(); //加载表头 IRow headerRow = sheet.GetRow(); ICell cellHeader = null; ICell cell = null; int cellCount = headerRow.LastCellNum; DateTime dtTmpTime = DateTime.Now; string Code; string Address; string regionid; string ToiletType; string area; string ManSquatting; string WomanSquatting; string ManagerPersonTel; string Jingdu; string Weidu; string ManagerPerson; string ClearPerson; string SuperviseTel; string opentype; string Remark; string status; string strTmpTime; string strCreTime; //遍历 ; i <= sheet.LastRowNum; i++) { ; try { row = sheet.GetRow(i); Toilet entity = new Toilet(); PcInfo para = new PcInfo(); ) { para = PcInfoLogic.GetEntity(EditId); } else { para = new PcInfo(); } //公厕编号 Code = row.GetCell().ToString(); if (!string.IsNullOrEmpty(Code)) { para.Name = Code; entity.Code = Code; } //详细位置 Address = row.GetCell().ToString(); if (!string.IsNullOrEmpty(Address)) { entity.Address = Convert.ToString(Address); para.Address = Convert.ToString(Address); } //区域名称返回区域编号 regionid = row.GetCell().ToString(); if (!string.IsNullOrEmpty(regionid)) { entity.RegionID = Convert.ToInt32(RegionID(regionid)); } //类型 ToiletType = row.GetCell().ToString(); if (!string.IsNullOrEmpty(ToiletType)) { entity.ToiletType = ToiletID(ToiletType); } //面积 area = row.GetCell().ToString(); if (!string.IsNullOrEmpty(area)) { entity.Area = ToiletID(area); } //男蹲位数 ManSquatting = row.GetCell().ToString(); if (!string.IsNullOrEmpty(ManSquatting)) { entity.ManSquatting = Convert.ToInt16(ManSquatting); } //女蹲位数 WomanSquatting = row.GetCell().ToString(); if (!string.IsNullOrEmpty(WomanSquatting)) { entity.WomanSquatting = Convert.ToInt16(WomanSquatting); } //经度 Jingdu = Convert.ToString(row.GetCell()); if (!string.IsNullOrEmpty(Jingdu)) { entity.Jingdu = Jingdu; } //维度 Weidu = Convert.ToString(row.GetCell()); if (!string.IsNullOrEmpty(Weidu)) { entity.Weidu = Weidu; } //建设时间 strTmpTime = Convert.ToString(row.GetCell()); if (!string.IsNullOrEmpty(strTmpTime)) { if (DateTime.TryParse(strTmpTime, out dtTmpTime)) { entity.BuildTime = dtTmpTime; } } //开门时间 strCreTime = Convert.ToString(row.GetCell()); if (!string.IsNullOrEmpty(strCreTime)) { if (DateTime.TryParse(strCreTime, out dtTmpTime)) { entity.DbCreateDate = dtTmpTime; } } //管理人 ManagerPerson = Convert.ToString(row.GetCell()); if (!string.IsNullOrEmpty(ManagerPerson)) { entity.ManagerPerson = ManagerPerson; } //管理人员电话 ManagerPersonTel = Convert.ToString(row.GetCell()); if (!string.IsNullOrEmpty(ManagerPersonTel)) { entity.ManagerPersonTel = ManagerPersonTel; } //保洁人员 ClearPerson = Convert.ToString(row.GetCell()); if (!string.IsNullOrEmpty(ClearPerson)) { entity.ClearPerson = ClearPerson; } //监督电话 SuperviseTel = Convert.ToString(row.GetCell()); if (!string.IsNullOrEmpty(SuperviseTel)) { entity.SuperviseTel = SuperviseTel; para.Phone = SuperviseTel; } //开放状态 opentype = OpenTypeID(row.GetCell().ToString()); if (!string.IsNullOrEmpty(opentype)) { entity.OpenType = Convert.ToInt32(opentype); } //影像URL Remark = Convert.ToString(row.GetCell().ToString()); if (!string.IsNullOrEmpty(Remark)) { entity.Remark = Remark; para.Desc = Remark; } //建设状态 status = StatusID(row.GetCell().ToString()); if (!string.IsNullOrEmpty(status)) { entity.Status = Convert.ToInt32(status); } ) { PcInfoLogic.Update(para); entity = ToiletLogic.GetEntity(EditId); } else { para.DbCreateDate = DateTime.Now; para.DbLastUpdateDate = DateTime.Now; para.DbCreateID = UserObject.UserID; para.MapData = new Microsoft.SqlServer.Types.SqlGeometry(); //公众服务信息表 PcInfoId = (int)PcInfoLogic.Insert(para); entity.ID = PcInfoId; } ) { entity.DbCreateDate = DateTime.Now; entity.DbCreateID = UserObject.UserID; //厕所表 ToiletLogic.Insert(entity); } else { ToiletLogic.Update(entity); } iAddedCount++; } catch { iFaileCount++; } } //回收资源 cellHeader = null; headerRow = null; } catch (Exception ex) { } finally { if (row != null) row = null; if (sheet != null) sheet = null; if (workBook != null) { //workBook.Clear(); workBook = null; } } } //删除文件 File.Delete(strPhysicalPath); //返回处理结果 //关闭窗口并刷新父窗口 base.WriteClientScript(string.Format("jUIDialog('导入成功{0}条,失败{1}条!{2}');", iAddedCount, iFaileCount, Msg) + "try{$(document).ready(function(){RelashParent();});}catch(e){}"); } //根据公厕名称获取公厕编号 public static string RegionID(string RegionName ) { DataTable ds = ToiletLogic.RegionID(RegionName); ][].ToString();; } //根据类型名称获取类型编号 public static int ToiletID(string ToiletName) { ; if (ToiletName=="移动厕所") { ToiletID= ; } else if (ToiletName=="一类水冲公厕") { ToiletID = ; } else { ToiletID = ; } return ToiletID; } //根据建设状态返回建设编号 public static string StatusID(string StatusName) { "; if (StatusName == "建成") { StatusID = "; } else { StatusID = "; } return StatusID; } //根据开放状态返回建设编号 public static string OpenTypeID(string OpenTypeName) { "; if (OpenTypeName == "开放") { OpenTypeID ="; } else { OpenTypeID ="; } return OpenTypeID; } } }
HttpPostedFile file = FileUpload1.PostedFile; string fileExt = Path.GetExtension(file.FileName); DataTable dt = new DataTable(); int mon = Convert.ToInt32(drpMonth.SelectedValue); int year = Convert.ToInt32(drpYear.SelectedValue); int times = DateTime.DaysInMonth(year, mon); if (fileExt != ".xls" && fileExt != ".xlsx") { } else { try { dt = ExcelToDatatable(file.InputStream).Select("c_grid is not null").CopyToDataTable(); } catch (Exception ex) { throw ex; //ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "<script language='javascript' type='text/javascript'>alert('读取数据出错,请检查文件格式是否正确后重试!');</script>"); } } private DataTable ExcelToDatatable(Stream inStream) { DataTable dt = new DataTable(); int mon =Convert.ToInt32(drpMonth.SelectedValue); int year = Convert.ToInt32(drpYear.SelectedValue); int times = DateTime.DaysInMonth(year, mon); ; using (HSSFWorkbook workbook = new HSSFWorkbook(inStream)) { HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(); System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); ; rows.MoveNext();//第一行没用 rows.MoveNext();//第二行没用 n++; string strGrid = ""; while (rows.MoveNext()) { HSSFRow row = (HSSFRow)rows.Current; )//定义列的行 { List<DataColumn> columnList = new List<DataColumn>() { new DataColumn("c_grid"), new DataColumn("c_name"), new DataColumn("c_date"), new DataColumn("c_1"), new DataColumn("c_2"), new DataColumn("c_3"), new DataColumn("c_4"), new DataColumn("c_5"), new DataColumn("c_6"), new DataColumn("c_7"), new DataColumn("c_8"), new DataColumn("c_9"), new DataColumn("c_10"), new DataColumn("c_11"), new DataColumn("c_12"), new DataColumn("c_13"), new DataColumn("c_14"), new DataColumn("c_15"), new DataColumn("c_16"), new DataColumn("c_17"), new DataColumn("c_18"), new DataColumn("c_19"), new DataColumn("c_20"), new DataColumn("c_21"), new DataColumn("c_22"), new DataColumn("c_23"), new DataColumn("c_24"), new DataColumn("c_25"), new DataColumn("c_26"), new DataColumn("c_27"), new DataColumn("c_28"), new DataColumn("c_29"), new DataColumn("c_30"), new DataColumn("c_31") }; foreach (DataColumn column in columnList) { dt.Columns.Add(column); } } else { DataRow dtRow = dt.NewRow(); //string rValue = ""; ; i <= dayCount; i++) { HSSFCell cell = (HSSFCell)row.GetCell(i); ) { if (cell == null) { dtRow[] = strGrid; } else { if (!string.IsNullOrEmpty(cell.ToString())) { strGrid = cell.ToString(); } dtRow[] = strGrid; } } else { if (cell == null) { dtRow[i - ] = ""; } else { dtRow[i - ] = cell.ToString(); } } } dt.Rows.Add(dtRow); } n++; } } return dt; }
NPOI导入xls,xlsx格式实例的更多相关文章
- POI使用:用poi接口不区分xls/xlsx格式解析Excel文档(41种日期格式解析方法,5种公式结果类型解析方法,3种常用数值类型精度控制办法)
一.使用poi解析excel文档 注:全部采用poi接口进行解析,不需要区分xls.xlsx格式,不需要判断文档类型. poi中的日期格式判断仅支持欧美日期习惯,对国内的日期格式并不支持判断,怎么办? ...
- 关于jquery js读取excel文件内容 xls xlsx格式 纯前端
附带参考:http://blog.csdn.net/gongzhongnian/article/details/76438555 更详细导入导出:https://www.jianshu.com/p/7 ...
- NPOI导入Excel日期格式的处理 - 附类型格式匹配表
传统操作Excel方法在部署的时候遇到很多问题,如目标主机需要安装Excel.64位电脑不支持.需要安装相关驱动程序等.所以我们一般会使用开源的NPOI来替代传统的Excel操作方法,NPOI的优点是 ...
- C# NPOI 导入与导出Excel文档 兼容xlsx, xls
之前写了个小程序,导出一些数据成Excel,程序使用的是Microsoft.Office.Interop.Excel类来操作Excel. 在本机测试的时候都好好的,但是将生成文件放到其他电脑上却怎样也 ...
- [转]C# NPOI 导入与导出Excel文档 兼容xlsx, xls
本文转自:https://www.cnblogs.com/lazyneal/p/6148912.html 参考:http://www.cnblogs.com/restran/p/3889479.htm ...
- NPOI 2.1.1 系列(1) 使用NPOI读取 Excel文档 ;NpoiExcelHelper 导入导出 2003格式 2007格式的 Excel; Npoi 导出 xlsx 格式
下载地址 http://npoi.codeplex.com/releases 下面放一个 NPOIHelper 助手类吧,也不是我写的- NpoiExcelHelper 可以生成xlsx格式publi ...
- C# NPOI 导入与导出Excel文档 兼容xlsx, xls(xf13中已经引用了xlsx的npoi)
这里使用的NPOI版本为: 2.1.3.1 官方下载地址: http://npoi.codeplex.com/releases 版本内包含.Net 2.0 与.Net 4.0 .Net 4.0中包含文 ...
- C# 将DataGridView中显示的数据导出到Excel(.xls和.xlsx格式)—NPOI
前言 https://blog.csdn.net/IT_xiao_guang_guang/article/details/104217491 本地数据库表中有46785条数据,测试正常 初次运行程 ...
- NPOI导入excel为datatable (xls xlsx xlsm)
使用NPOI导入导出Excel(xls/xlsx)数据到DataTable中 http://www.cnblogs.com/songrun/p/3547738.html NPOI 2.0教程 – 自动 ...
随机推荐
- Sqlserver 导出数据脚本
编写数据压缩选项的脚本 true 要编写脚本的数据的类型 仅限数据
- js实现下滑加载更多的效果
var stop=true;$(window).scroll(function(){ totalheight = parseFloat($(window).height()) + parseFloat ...
- linux 安装配置Nginx
简介: Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like 协议下发行.由俄罗斯的程序设计师Igor Sysoev所开发,供俄国 ...
- lua unit test introduction
Unit Test Unit testing is about testing your code during development, not in production. Typically y ...
- css3水波纹效果
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- cms 常用标签
{template "content","header"} 调用根目录下phpcms\template\content\header文件 {CHARSET} 字 ...
- Android 多媒体视频播放一( 多媒体理解与经验分享)
前言 说到android的多媒体,一把辛酸一把泪,当初听说会多媒体的比较牛掰,公司也有需求,于是乎我也积极的加入研究android多媒体的行列,记得以前刚接触的时候,最开始还是比较头大的,主要是但是很 ...
- git基本配置
用户信息 你个人的用户名称和电子邮件地址,用户名可随意修改,git 用于记录是谁提交了更新,以及更新人的联系方式. $ git config --global user.name "Donl ...
- cmd光标移动
ESC:清除当前命令行.F1: 单字符输出上次输入的命令 相当于方向键上的 → 的作用.F2: 可复制字符数量 , 输入上次命令中含有的字符,系统自动删除此字符后的内容.F3: 重新输入前一次输入的命 ...
- Java多线程开发系列之一:走进多线程
对编程语言的基础知识:分支.选择.循环.面向对象等基本概念理解后,我们需要对java高级编程有一定的学习,这里不可避免的要接触到多线程开发. 由于多线程开发整体的系统比较大,我会写一个系列的文章总结介 ...