关于NPOI导入导出
http://www.360doc.com/content/14/0110/16/432969_344152497.shtml
NPOI汇入Excel仅支持2007版本以内:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (Request.Files["file"].ContentLength > 0)
{
// 获取文件拓展名
string extension = Path.GetExtension(file.FileName);
if (extension == ".xls" || extension == ".xlsx")
{
string fileLocation = Server.MapPath("~/Content/") + Request.Files["file"].FileName;
// 验证文件是否存在,如果存在就删除
if (System.IO.File.Exists(fileLocation))
{
System.IO.File.Delete(fileLocation);
}
// 将文件上传到服务器
Request.Files["file"].SaveAs(fileLocation);
HSSFWorkbook excel;
using (FileStream files = new FileStream(fileLocation, FileMode.Open, FileAccess.Read))
{
excel = new HSSFWorkbook(files);
//
ISheet sheet = excel.GetSheetAt(0);
// 使用名称获取
ISheet sheetb = excel.GetSheet("Name");
for (int row = 0; row <= sheet.LastRowNum; row++)
{
string name = null;
int age = 0;
if (sheet.GetRow(row) != null)
{
name = sheet.GetRow(row).GetCell(0).StringCellValue;
age = Convert.ToInt32(sheet.GetRow(row).GetCell(1).NumericCellValue);
}
else
{
continue;
}
Users users = new Users();
users.Name = name;
users.Age = age;
db.users.Add(users);
}
db.SaveChanges();
}
}
}
return this.RedirectToAction("Index");
}
NPOI汇入Excel支持2007版本以上:(注意需要引入NPOI.dll,NPOI.OOXML.dll,NPOI.OpenXml4Net.dll,参照文件NPOI2.2.0.zip)
public ActionResult Upload(HttpPostedFileBase file)
{
if (Request.Files["file"].ContentLength > 0)
{
// 获取文件拓展名
string extension = Path.GetExtension(file.FileName);
if (extension == ".xls" || extension == ".xlsx")
{
string fileLocation = Server.MapPath("~/Content/") + Request.Files["file"].FileName;
// 验证文件是否存在,如果存在就删除
if (System.IO.File.Exists(fileLocation))
{
System.IO.File.Delete(fileLocation);
}
// 将文件上传到服务器
Request.Files["file"].SaveAs(fileLocation);
//HSSFWorkbook excel;
using (FileStream files = new FileStream(fileLocation, FileMode.Open, FileAccess.Read))
{
NPOI.SS.UserModel.IWorkbook userModel;
try
{
userModel = new NPOI.XSSF.UserModel.XSSFWorkbook(files); // 2007 格式
}
catch (Exception)
{
userModel = new NPOI.HSSF.UserModel.HSSFWorkbook(files); // 2003 格式
}
finally
{
files.Close();
}
//excel = new HSSFWorkbook(files);
// ISheet sheet = userModel.GetSheetAt(0);
// 使用名称获取
ISheet sheetb = userModel.GetSheet("Name");
for (int row = 0; row <= sheet.LastRowNum; row++)
{
string name = null;
int age = 0;
if (sheet.GetRow(row) != null)
{
name = sheet.GetRow(row).GetCell(0).StringCellValue;
age = Convert.ToInt32(sheet.GetRow(row).GetCell(1).NumericCellValue);
//for (int i = 0; i <= sheet.GetRow(row).LastCellNum; i++)
//{
// name = sheet.GetRow(row).GetCell(i).StringCellValue;
// age = Convert.ToInt32(sheet.GetRow(row).GetCell(i+1).NumericCellValue);
// //sheet.GetRow(row).GetCell(i).NumericCellValue; // 數值
// //sheet.GetRow(row).GetCell(i).StringCellValue; // 字串
// //sheet.GetRow(row).GetCell(i).BooleanCellValue; // 布林
// //sheet.GetRow(row).GetCell(i).DateCellValue; // 日期
//}
}
else
{
continue;
}
// 创建对象存入DB
Users users = new Users();
users.Name = name;
users.Age = age;
db.users.Add(users);
}
db.SaveChanges();
}
}
}
===================================================================================
NPOI汇出Excel:
/// <summary>
/// 将页面资料汇入指定 Excel 的多个 Sheet
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="strFileName"></param>
/// <param name="lstNew"></param>
private void ExpMultiSheetToExcel<T>(string strFileName, List<T> lstNew)
{
try
{
if (strFileName != null && lstNew != null)
{
// 創建Excel文件的對象
HSSFWorkbook workbook = new HSSFWorkbook();
PropertyInfo[] newDataDest = lstNew[0].GetType().GetProperties();
int i = 1;
foreach (PropertyInfo newProperty in newDataDest)
{
dynamic newDic1 = newProperty.GetValue(lstNew[0]);
int newDataIndex1 = 0;
foreach (var newKey in newDic1.Keys)
{
if (newKey != null)
{
// 添加一個sheet
ISheet sheetEmp = workbook.CreateSheet(newKey);
dynamic lstNewDate = newDic1[newKey];
//將數據寫入sheetEmp的各個行
for (int intIndex = 0; intIndex < lstNewDate.Count; intIndex++)
{
// JKBaseInfo ALL Property
PropertyInfo[] propertiesDest = lstNewDate[intIndex].GetType().GetProperties();
IRow row0 = sheetEmp.CreateRow(0);
IRow rowtemp = sheetEmp.CreateRow(intIndex + 1);
int columnIndex = 0;
foreach (PropertyInfo property in propertiesDest)
{
Dictionary<string, string> dic = property.GetValue(lstNewDate[intIndex]) as Dictionary<string, string>;
foreach (var key in dic.Keys)
{
row0.CreateCell(columnIndex).SetCellValue(key);
// Value
if (row0.GetCell(columnIndex).ToString().Contains(key)) {
string obj = dic[key];
rowtemp.CreateCell(columnIndex).SetCellValue(obj);
}
}
columnIndex++;
}
}
newDataIndex1++;
}
}
}
// 寫入到客戶端
MemoryStream ms = new MemoryStream();
workbook.Write(ms);
FileStream fs = new FileStream(strFileName + ".xls", FileMode.OpenOrCreate);
BinaryWriter w = new BinaryWriter(fs);
w.Write(ms.ToArray());
fs.Close();
workbook = null;
ms.Close();
ms.Dispose();
}
}
catch (Exception ex) { throw ex; } }
/// <summary>
/// 匯出个人健康档案數據到Excel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toExcel()
{
try
{
// 創建Excel文件的對象
HSSFWorkbook workbook = new HSSFWorkbook();
// 添加一個sheet
ISheet sheetEmp = workbook.CreateSheet("sheet1");
// 獲得List數據 List<BaseInfo> lstInfo = lstBaseInfo;
// 給sheet添加第一行的頭部標題 IRow row1 = sheetEmp.CreateRow(0); row1.CreateCell(0).SetCellValue("与户主关系"); row1.CreateCell(1).SetCellValue("档案状态"); row1.CreateCell(2).SetCellValue("姓名"); row1.CreateCell(3).SetCellValue("性别"); row1.CreateCell(4).SetCellValue("证件编号"); row1.CreateCell(5).SetCellValue("出生日期"); row1.CreateCell(6).SetCellValue("本人电话"); row1.CreateCell(7).SetCellValue("工作单位"); row1.CreateCell(8).SetCellValue("联系人电话"); row1.CreateCell(9).SetCellValue("联系人姓名"); row1.CreateCell(10).SetCellValue("常住类型"); row1.CreateCell(11).SetCellValue("民族"); row1.CreateCell(12).SetCellValue("血型"); row1.CreateCell(13).SetCellValue("RH"); row1.CreateCell(14).SetCellValue("职业"); row1.CreateCell(15).SetCellValue("文化程度"); row1.CreateCell(16).SetCellValue("劳动程度"); row1.CreateCell(17).SetCellValue("婚姻状况");
row1.CreateCell(18).SetCellValue("医疗费用支付方式"); row1.CreateCell(19).SetCellValue("医疗保险号"); row1.CreateCell(20).SetCellValue("新农合号"); row1.CreateCell(21).SetCellValue("居住地址"); row1.CreateCell(22).SetCellValue("所属片区"); row1.CreateCell(23).SetCellValue("档案类别"); row1.CreateCell(24).SetCellValue("药物过敏史"); row1.CreateCell(25).SetCellValue("既往史"); row1.CreateCell(26).SetCellValue("家族史"); row1.CreateCell(27).SetCellValue("暴露史"); row1.CreateCell(28).SetCellValue("遗传病史"); row1.CreateCell(29).SetCellValue("残疾状况"); row1.CreateCell(30).SetCellValue("生活环境"); row1.CreateCell(31).SetCellValue("调查时间"); row1.CreateCell(32).SetCellValue("录入时间"); row1.CreateCell(33).SetCellValue("录入人"); row1.CreateCell(34).SetCellValue("最近更新时间"); row1.CreateCell(35).SetCellValue("最近修改人"); row1.CreateCell(36).SetCellValue("当前所属机构");
//將數據寫入sheetEmp的各個行 for (int i = 0; i < lstInfo.Count; i++) { IRow rowtemp = sheetEmp.CreateRow(i + 1); rowtemp.CreateCell(0).SetCellValue(lstInfo[i].huzhu); rowtemp.CreateCell(1).SetCellValue(lstInfo[i].daState); rowtemp.CreateCell(2).SetCellValue(lstInfo[i].Name); rowtemp.CreateCell(3).SetCellValue(lstInfo[i].Sex); rowtemp.CreateCell(4).SetCellValue(lstInfo[i].zjNum); rowtemp.CreateCell(5).SetCellValue(lstInfo[i].Birthday); rowtemp.CreateCell(6).SetCellValue(lstInfo[i].MobileTel); rowtemp.CreateCell(7).SetCellValue(lstInfo[i].WorkAddr); rowtemp.CreateCell(8).SetCellValue(lstInfo[i].HomeTel); rowtemp.CreateCell(9).SetCellValue(lstInfo[i].RelativeName); rowtemp.CreateCell(10).SetCellValue(lstInfo[i].changzhuType); rowtemp.CreateCell(11).SetCellValue(lstInfo[i].minzu); rowtemp.CreateCell(12).SetCellValue(lstInfo[i].xuexing); rowtemp.CreateCell(13).SetCellValue(lstInfo[i].RH); rowtemp.CreateCell(14).SetCellValue(lstInfo[i].job); rowtemp.CreateCell(15).SetCellValue(lstInfo[i].wenhuachengdu); rowtemp.CreateCell(16).SetCellValue(lstInfo[i].laodongchengdu); rowtemp.CreateCell(17).SetCellValue(lstInfo[i].marry);
rowtemp.CreateCell(18).SetCellValue(lstInfo[i].yiliaofeiyong); rowtemp.CreateCell(19).SetCellValue(lstInfo[i].yiliaobaoxianhao); rowtemp.CreateCell(20).SetCellValue(lstInfo[i].xinnonghehao); rowtemp.CreateCell(21).SetCellValue(lstInfo[i].juzhudizhi); rowtemp.CreateCell(22).SetCellValue(lstInfo[i].suoshupianqu); rowtemp.CreateCell(23).SetCellValue(lstInfo[i].danganleibie); rowtemp.CreateCell(24).SetCellValue(lstInfo[i].yaowuguominshi); rowtemp.CreateCell(25).SetCellValue("疾病:" + lstInfo[i].jibing + ";手术:" + lstInfo[i].shoushu + ";外伤:" + lstInfo[i].waishang + ";输血:" + lstInfo[i].shuxie); rowtemp.CreateCell(26).SetCellValue(lstInfo[i].jiazushi); rowtemp.CreateCell(27).SetCellValue(lstInfo[i].baolushi); rowtemp.CreateCell(28).SetCellValue(lstInfo[i].yichuanbingshi); rowtemp.CreateCell(29).SetCellValue(lstInfo[i].jibingzhuangkuang); rowtemp.CreateCell(30).SetCellValue("厨房排风设施:" + (lstInfo[i].chufang == null ? "无" : lstInfo[i].chufang) + "; 燃料类型:" + (lstInfo[i].ranliao == null ? "无" : lstInfo[i].ranliao) + ";饮水:" + (lstInfo[i].yinshui == null ? "无" : lstInfo[i].yinshui) + ";厕所:" + (lstInfo[i].cesuo == null ? "无" : lstInfo[i].cesuo) + ";禽畜栏:" + (lstInfo[i].qinchu == null ? "无" : lstInfo[i].qinchu)); rowtemp.CreateCell(31).SetCellValue(lstInfo[i].diaochashijian); rowtemp.CreateCell(32).SetCellValue(lstInfo[i].lurushijian); rowtemp.CreateCell(33).SetCellValue(lstInfo[i].lururen); rowtemp.CreateCell(34).SetCellValue(lstInfo[i].zuijingengxinshijian); rowtemp.CreateCell(35).SetCellValue(lstInfo[i].zuijinxiugairen); rowtemp.CreateCell(36).SetCellValue(lstInfo[i].dqsuoshujigou); }
// 寫入到客戶端 MemoryStream ms = new MemoryStream(); workbook.Write(ms); FileStream fs = new FileStream("个人基本信息.xls", FileMode.OpenOrCreate); BinaryWriter w = new BinaryWriter(fs); w.Write(ms.ToArray()); fs.Close(); workbook = null; ms.Close(); ms.Dispose(); } catch (Exception ex) { throw ex; } }
关于NPOI导入导出的更多相关文章
- c# .Net :Excel NPOI导入导出操作教程之读取Excel文件信息及输出
c# .Net :Excel NPOI导入导出操作教程之读取Excel文件信息及输出 using NPOI.HSSF.UserModel;using NPOI.SS.UserModel;using S ...
- NPOI导入导出EXCEL通用类,供参考,可直接使用在WinForm项目中
以下是NPOI导入导出EXCEL通用类,是在别人的代码上进行优化的,兼容xls与xlsx文件格式,供参考,可直接使用在WinForm项目中,由于XSSFWorkbook类型的Write方法限制,Wri ...
- NPOI导入导出Excel
.net mvc利用NPOI导入导出excel 注意:如何导出的提交方式ajax导出是失效的! 解决方案是:js处理l两个表单的提交 代码: 第一步. 在页面里面加入2个隐藏的iframe, 如下 ...
- .Net core NPOI导入导出Excel
最近在想.net core NPOI 导入导出Excel,一开始感觉挺简单的,后来真的遇到很多坑.所以还是写一篇博客让其他人少走一些弯路,也方便忘记了再重温一遍.好了,多的不说,直接开始吧. 在.Ne ...
- c#.net 使用NPOI导入导出标准Excel (asp.net winform csharp)
尝试过很多Excel导入导出方法,都不太理想,无意中逛到oschina时,发现了NPOI,无需Office COM组件且不依赖Office,顿时惊为天人,怀着无比激动的心情写下此文. 曾使用过的方法 ...
- 使用NPOI导入导出标准的Excel
关于NPOI NPOI是POI项目的.NET版本,是由@Tony Qu(http://tonyqus.cnblogs.com/)等大侠基于POI开发的,可以从http://npoi.codeplex. ...
- ASP.NET- 使用NPOI导入导出标准Excel
尝试过很多Excel导入导出方法,都不太理想,无意中逛到oschina时,发现了NPOI,无需Office COM组件且不依赖Office,顿时惊为天人,怀着无比激动的心情写下此文. 曾使用过的方法 ...
- 使用NPOI导入导出标准Excel
尝试过很多Excel导入导出方法,都不太理想,无意中逛到oschina时,发现了NPOI,无需Office COM组件且不依赖Office,顿时惊为天人,怀着无比激动的心情写下此文. 曾使用过的方法 ...
- NPOI导入导出Excel数据
代码: using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; usi ...
- net core WebApi——使用NPOI导入导出操作
目录 前言 NPOI 测试 小结 @ 前言 时间过得好快,在之前升级到3.0之后,就感觉好久没再动过啥东西了,之前有问到Swagger的中文汉化,虽说我觉得这种操作的意义不是太大,也是多少鼓捣了下,其 ...
随机推荐
- MVC将服务器端的物理路径转换为服务器路径
以图片为例 后台Controller.cs public FileResult ImageUrl(string file) { return File("物理路径"+file, & ...
- oracle启动脚本 .
.#!/bin/bash set -x su -oracle >>EON lsnrctl start sqlplus /nolog >>EOF conn / as sy ...
- python学习之——安装Beautifulsoup、requests、lxml
安装Beautiful soup: 1.下载安装包,解压到python的安装目录: 2.cmd 进入安装包解压后的存放位置: 3.使用命令:python setup.py build , pyt ...
- Spring MVC CORS support
使用详见: https://spring.io/blog/2015/06/08/cors-support-in-spring-framework 简单用法,在Controller 方法上加 @Cros ...
- jdk安装和环境变量配置
jdk的安装和环境变量配置每次换新环境都在做,但是每次都没有认真去想是怎么做的,反正每次打开百度搜索照做就是.这次整理一下,也顺便理清一下其中的原理. 1.第一步当然就是下载jdk,我这边下载的是jd ...
- Spring SpringMVC和Mybatis整合
1.引入所要的jar包 2.创建Mybatis的sqlMapConfig.xml配置文件,该文件中可以配置mybaits的相关参数,数据源不在这里配置. <?xml version=" ...
- 粗略读完opengl
清明节前粗略读完了opengl编程指南第七版,对opengl有了一个大体的了解,并且了解的也很肤浅.有了计算机图形学,线性代数的基础,读起来也不像以前那么吃力了.从简单的绘制点,直线,多边形,到视图变 ...
- 移动APP开发使用什么样的原型设计工具比较合适?
原型设计工具有Axure,Balsamiq Mockups,JustinMind,iClap原型工具,等其他原型工具.其中JustinMind比较适合APP开发使用. JustinMind可以输出Ht ...
- 20145318 GDB调试汇编堆栈分析
20145318 GDB调试汇编堆栈分析 代码 #include<stdio.h> short addend1 = 1; static int addend2 = 2; const sta ...
- [php-src]窥探Php内核中的数组与面向对象
内容均以php5.6.14为例. 扩展中定义一个类有以下四步: #1. 声明一个存储类信息的指针. zend_class_entry *errs_ce; #2. 定义方法的参数信息,类的方法实现. Z ...