关于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的中文汉化,虽说我觉得这种操作的意义不是太大,也是多少鼓捣了下,其 ...
随机推荐
- 启动Tomcat时报 Expected stackmap frame at this location.(JDK1.7编译)
从svn上下的项目,部署到tomcat 7.0.19 上, 并且配置的是jdk7. 启动时出现以下问题. Location: com/genlot/loms/service/SysPermissio ...
- Reverse链表 非递归实现
#include<iostream> struct node{ int payload; node* next; }; void bianli(node* head){ node* ite ...
- jquery获取所有被选中checkbox
想要得到所有被选中的checkbox的value ,并且传给后台 var headers = ""; $('input[name="header"]:check ...
- subversion
yum install apr-util-devel.x86_64 sqlite-devel https://subversion.apache.org/download.cgi ./configur ...
- c# DESEncrypt 加密、解密算法
using System; using System.Security.Cryptography; using System.Text; namespace AttendService { publi ...
- C#邮箱发送验证码
public static void SendTo(string mailAddress, string subject, string body) { //mailAddress 所要 ...
- 百度UEditor基本使用
1 首先奉上链接其http://ueditor.baidu.com/website/index.html 更多更详细内容在其官方api上,本文只是一个归类总结性文章. 2 下载链接http://ued ...
- 「脑洞」图片转HTML(支持动画)
也许是受到很久以前看到的这玩意儿的原因:The Shapes of CSS 现在开脑洞写了个自动转换,顺便支持了动画……嗯,纯 CSS (:з」∠) 主要步骤就是用 Python 读图片,然后把像素全 ...
- XE3随笔16:将字符串转换成 UTF8 编码的函数
这种转换一般用于网页地址; 我不知道 Delphi 是不是有现成的函数, 用到了就写了一个. //函数: function ToUTF8Encode(str: string): string; var ...
- M2事后分析汇报总结
学霸网站项目Postmortem结果 M2之于M1的改进 文档和问答的整合 完成webservice 完成数据库触发器设计与完整性约束依赖(大规模) 优化学霸UI 资源的搜索 外部问题的搜索 文档的上 ...