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导入导出的更多相关文章

  1. c# .Net :Excel NPOI导入导出操作教程之读取Excel文件信息及输出

    c# .Net :Excel NPOI导入导出操作教程之读取Excel文件信息及输出 using NPOI.HSSF.UserModel;using NPOI.SS.UserModel;using S ...

  2. NPOI导入导出EXCEL通用类,供参考,可直接使用在WinForm项目中

    以下是NPOI导入导出EXCEL通用类,是在别人的代码上进行优化的,兼容xls与xlsx文件格式,供参考,可直接使用在WinForm项目中,由于XSSFWorkbook类型的Write方法限制,Wri ...

  3. NPOI导入导出Excel

    .net mvc利用NPOI导入导出excel 注意:如何导出的提交方式ajax导出是失效的! 解决方案是:js处理l两个表单的提交  代码:  第一步. 在页面里面加入2个隐藏的iframe, 如下 ...

  4. .Net core NPOI导入导出Excel

    最近在想.net core NPOI 导入导出Excel,一开始感觉挺简单的,后来真的遇到很多坑.所以还是写一篇博客让其他人少走一些弯路,也方便忘记了再重温一遍.好了,多的不说,直接开始吧. 在.Ne ...

  5. c#.net 使用NPOI导入导出标准Excel (asp.net winform csharp)

    尝试过很多Excel导入导出方法,都不太理想,无意中逛到oschina时,发现了NPOI,无需Office COM组件且不依赖Office,顿时惊为天人,怀着无比激动的心情写下此文. 曾使用过的方法 ...

  6. 使用NPOI导入导出标准的Excel

    关于NPOI NPOI是POI项目的.NET版本,是由@Tony Qu(http://tonyqus.cnblogs.com/)等大侠基于POI开发的,可以从http://npoi.codeplex. ...

  7. ASP.NET- 使用NPOI导入导出标准Excel

    尝试过很多Excel导入导出方法,都不太理想,无意中逛到oschina时,发现了NPOI,无需Office COM组件且不依赖Office,顿时惊为天人,怀着无比激动的心情写下此文. 曾使用过的方法 ...

  8. 使用NPOI导入导出标准Excel

    尝试过很多Excel导入导出方法,都不太理想,无意中逛到oschina时,发现了NPOI,无需Office COM组件且不依赖Office,顿时惊为天人,怀着无比激动的心情写下此文. 曾使用过的方法 ...

  9. NPOI导入导出Excel数据

    代码: using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; usi ...

  10. net core WebApi——使用NPOI导入导出操作

    目录 前言 NPOI 测试 小结 @ 前言 时间过得好快,在之前升级到3.0之后,就感觉好久没再动过啥东西了,之前有问到Swagger的中文汉化,虽说我觉得这种操作的意义不是太大,也是多少鼓捣了下,其 ...

随机推荐

  1. mvc 4 ActionFilterAttribute 特性,进行权限验证

    权限验证: /// <summary> /// 管理员身份验证 /// </summary> public class BasicAuthenticationAttribute ...

  2. 对CPU做下性能测试

    任务管理器里把pi.exe优先级调到“高” I5-4308U  (2.80Ghz)     PI-1M最佳成绩11.719秒(MACBOOK PRO 13inch,插电,电源选择高性能模式) G202 ...

  3. 模拟器报Installation error: INSTALL_FAILED_CONTAINER_ERROR解决方法

    今天刚刚导入了一个项目,但是多次导入,始终有错误,解决不了.第一次是我导入项目之后,项目前边有红色叉号,但是项目里面却没有错误标志.重新打开Eclipse,方解决了这个问题.但是,在模拟器上运行,却始 ...

  4. X64操作系统组件Jmail无法正常服务问题

    故障现象: 近日,在VMware虚拟化部署迁移中,之前物理服务器中部署网站ASP组件Jmail服务一切正常,迁移完成后发现Jmail无法正常工作,其余组件能正常工作. 环境:Windows Serve ...

  5. c++ 覆盖、重载与隐藏

    成员函数被重载的特征:(1)相同的范围(在同一个类中):(2)函数名字相同:(3)参数不同:(4)virtual 关键字可有可无.覆盖是指派生类函数覆盖基类函数,特征是:(1)不同的范围(分别位于派生 ...

  6. 编译安装或者mysql启动时遇到的错误小记

    编译安装遇到的错误:进入mysql目录 [root@localhost software]# cd mysql-5.6.19 [root@localhost mysql-5.5.11]# cmake ...

  7. DSP(2) -- 离散时间信号的序列运算

    1.信号相加:这是一种对应的样本与样本之间的相加. 在Matlab中它可用算术运算符“+”实现,然后x1和x2的长度必须相等.如果序列不等,或者长度虽然相等但采样的位置不同,就不能用运算符“+”了.我 ...

  8. jetbrains产品激活方式(WebStorm,Pycharm有效)

    注册时,在打开的License Activation窗口中选择"activation code",在输入框输入下面的注册码 43B4A73YYJ-eyJsaWNlbnNlSWQiO ...

  9. ORACLE RAC 11G 更改 /etc/hosts文件

    来自官方文档:()Can I change the public hostname in my Oracle Database 10g Cluster using Oracle Clusterware ...

  10. PHP获取当前服务器信息的基本语句

    下面是PHP获取当前服务器信息的基本语句. PHP程式版本: <?PHP echo PHP_VERSION; ?> ZEND版本: <?PHP echo zend_version() ...