因为微软的office成本太高了,所以开发项目的时候电脑上没安装office,而是安装了wps。但开发语言用的是C#,所以直接调用微软的office组件是很方便的,但一方面慢,一方面成本高,所以从网上找到了NPOI这个开源的项目。http://npoi.codeplex.com/,引用的dll下载目录 http://npoi.codeplex.com/downloads/get/1476595

并且封装了通用的处理EXCEL 跟DataSet,DataTable的方法。方便调用

以上是代码 (当前项目是.net 2.0 下的,如果需要.net 4.0则到NPOI官网下载相应的dll就可以了)

 using NPOI.SS.UserModel;
 using System;
 using System.Collections.Generic;
 using System.Data;
 using System.IO;
 using System.Text;

 namespace MrLiu.Tools
 {
     public sealed class ExcelHelper
     {
         #region Excel导入
         /// <summary>
         /// Excel 转换为DataTable
         /// </summary>
         /// <param name="file">文件路径</param>
         /// <param name="sheetName">Sheet名称,如果只有一个sheet可以传 null</param>
         /// <returns></returns>
         public static DataTable ExcelToDataTable(string file, string sheetName)
         {
             try
             {
                 DataTable dt = new DataTable();
                 using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
                 {
                     var workbook = NPOI.SS.UserModel.WorkbookFactory.Create(fs);
                     ISheet sheet = null;
                     if (sheetName == null)
                     {
                         sheet = workbook.GetSheetAt();
                     }
                     else
                     {
                         sheet = workbook.GetSheet(sheetName);
                     }
                     //列名
                     IRow rowHead = sheet.GetRow(sheet.FirstRowNum);
                     ; i < rowHead.LastCellNum; i++)
                     {
                         string fildName = rowHead.GetCell(i).StringCellValue;
                         dt.Columns.Add(fildName, typeof(String));
                     }

                     //数据
                     ; i <= sheet.LastRowNum; i++)
                     {
                         IRow row = sheet.GetRow(i);
                         DataRow dr = dt.NewRow();
                         for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
                         {
                             var cell = row.GetCell(j);
                             dr[j] = GetValueTypeForICell(cell);
                             if (dr[j] == null)
                             {
                                 dr[j] = string.Empty;
                             }
                         }
                         dt.Rows.Add(dr);
                     }
                 }
                 return dt;
             }
             catch (Exception ex)
             {
                 throw new Exception(ex.Message);
             }
         }
         /// <summary>
         /// Excel 导入为DataTable
         /// </summary>
         /// <param name="file">文件路径</param>
         /// <param name="extension">后续名 XLS XLSX</param>
         /// <returns></returns>
         public static DataTable ExcelToDataTable(string file)
         {
             try
             {
                 DataTable dt = new DataTable();
                 string extension = Path.GetExtension(file);
                 if (extension.ToUpper() == ".XLS")
                 {
                     dt = ExcelToTableForXLS(file);
                 }
                 else if (extension.ToUpper() == ".XLS")
                 {
                     dt = ExcelToTableForXLSX(file);
                 }
                 else
                 {
                     throw new Exception("文件格式不正确");
                 }
                 return dt;
             }
             catch (Exception ex)
             {
                 throw new Exception(ex.Message);
             }
         }
         /// <summary>
         /// 读取xls格式的Excel
         /// </summary>
         /// <param name="file">文件全路径</param>
         /// <returns>返回DaTaTable</returns>
         public static DataTable ExcelToTableForXLS(string file)
         {
             try
             {
                 DataTable dt = new DataTable();
                 using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
                 {
                     var hssfworkbook = new NPOI.HSSF.UserModel.HSSFWorkbook(fs);
                     ISheet sheet = hssfworkbook.GetSheetAt();

                     //列名
                     IRow rowHead = sheet.GetRow(sheet.FirstRowNum);
                     ; i < rowHead.LastCellNum; i++)
                     {
                         string fildName = rowHead.GetCell(i).StringCellValue;
                         dt.Columns.Add(fildName, typeof(String));
                     }

                     //数据
                     ; i <= sheet.LastRowNum; i++)
                     {
                         IRow row = sheet.GetRow(i);
                         DataRow dr = dt.NewRow();
                         for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
                         {
                             NPOI.HSSF.UserModel.HSSFCell cell = row.GetCell(j) as NPOI.HSSF.UserModel.HSSFCell;
                             dr[j] = GetValueTypeForXLS(cell);
                             if (dr[j] == null)
                             {
                                 break;
                             }
                         }
                         dt.Rows.Add(dr);
                     }
                 }
                 return dt;
             }
             catch (Exception ex)
             {
                 throw new Exception(ex.Message);
             }
         }

         /// <summary>
         /// 获取单元格类型
         /// </summary>
         /// <param name="cell"></param>
         /// <returns></returns>
         private static object GetValueTypeForXLS(NPOI.HSSF.UserModel.HSSFCell cell)
         {
             try
             {
                 if (cell == null)
                 {
                     return null;
                 }
                 switch (cell.CellType)
                 {
                     case CellType.Blank: //BLANK:
                         return null;
                     case CellType.Boolean: //BOOLEAN:
                         return cell.BooleanCellValue;
                     case CellType.Numeric: //NUMERIC:
                         return cell.NumericCellValue;
                     case CellType.String: //STRING:
                         return cell.StringCellValue;
                     case CellType.Error: //ERROR:
                         return cell.ErrorCellValue;
                     case CellType.Formula: //FORMULA:
                     default:
                         return "=" + cell.CellFormula;
                 }
             }
             catch (Exception ex)
             {
                 throw new Exception(ex.Message);
             }
         }

         /// <summary>
         /// 读取xlsx格式的Excel
         /// </summary>
         /// <param name="file">文件全路径</param>
         /// <returns>返回DaTaTable</returns>
         public static DataTable ExcelToTableForXLSX(string file)
         {
             try
             {
                 DataTable dt = new DataTable();
                 using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
                 {
                     var hssfworkbook = new NPOI.XSSF.UserModel.XSSFWorkbook(fs);
                     ISheet sheet = hssfworkbook.GetSheetAt();

                     //列名
                     IRow rowHead = sheet.GetRow(sheet.FirstRowNum);
                     ; i < rowHead.LastCellNum; i++)
                     {
                         string fildName = rowHead.GetCell(i).StringCellValue;
                         dt.Columns.Add(fildName, typeof(String));
                     }

                     //数据
                     ; i <= sheet.LastRowNum; i++)
                     {
                         IRow row = sheet.GetRow(i);
                         DataRow dr = dt.NewRow();
                         for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
                         {
                             NPOI.HSSF.UserModel.HSSFCell cell = row.GetCell(j) as NPOI.HSSF.UserModel.HSSFCell;
                             dr[j] = GetValueTypeForXLS(cell);
                             if (dr[j] == null)
                             {
                                 break;
                             }
                         }
                         dt.Rows.Add(dr);
                     }
                 }
                 return dt;
             }
             catch (Exception ex)
             {
                 throw new Exception(ex.Message);
             }
         }
         /// <summary>
         /// 获取单元格类型(xlsx)
         /// </summary>
         /// <param name="cell"></param>
         /// <returns></returns>
         private static object GetValueTypeForXLSX(NPOI.XSSF.UserModel.XSSFCell cell)
         {
             try
             {
                 if (cell == null)
                 {
                     return null;
                 }
                 switch (cell.CellType)
                 {
                     case CellType.Blank: //BLANK:
                         return null;
                     case CellType.Boolean: //BOOLEAN:
                         return cell.BooleanCellValue;
                     case CellType.Numeric: //NUMERIC:
                         return cell.NumericCellValue;
                     case CellType.String: //STRING:
                         return cell.StringCellValue;
                     case CellType.Error: //ERROR:
                         return cell.ErrorCellValue;
                     case CellType.Formula: //FORMULA:
                     default:
                         return "=" + cell.CellFormula;
                 }
             }
             catch (Exception ex)
             {
                 throw new Exception(ex.Message);
             }
         }

         /// <summary>
         /// 获取单元格类型不定
         /// </summary>
         /// <param name="cell"></param>
         /// <returns></returns>
         private static object GetValueTypeForICell(ICell cell)
         {
             try
             {
                 if (cell == null)
                 {
                     return null;
                 }
                 switch (cell.CellType)
                 {
                     case CellType.Blank: //BLANK:
                         return null;
                     case CellType.Boolean: //BOOLEAN:
                         return cell.BooleanCellValue;
                     case CellType.Numeric: //NUMERIC:
                         return cell.NumericCellValue;
                     case CellType.String: //STRING:
                         return cell.StringCellValue;
                     case CellType.Error: //ERROR:
                         return cell.ErrorCellValue;
                     case CellType.Formula: //FORMULA:
                     default:
                         return "=" + cell.CellFormula;
                 }
             }
             catch (Exception ex)
             {
                 throw new Exception(ex.Message);
             }
         }

         /// <summary>
         /// Excel 转换为DataSet
         /// </summary>
         /// <param name="fileName">文件名</param>
         /// <returns>DataSet</returns>
         public static DataSet ExcelToDataSet(string fileName)
         {
             try
             {
                 if (!File.Exists(fileName))
                 {
                     throw new Exception("文件不存在");
                 }
                 else
                 {
                     DataSet ds = new DataSet();
                     using (FileStream reader = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                     {
                         IWorkbook book = WorkbookFactory.Create(reader);
                         int cnt = book.NumberOfSheets;
                         )
                         {
                             throw new Exception("文件不是Excel文件");
                         }

                         ; i < cnt; i++)
                         {
                             ISheet sheet = book.GetSheetAt(i);
                             DataTable dt = new DataTable(sheet.SheetName);
                             IRow rowHead = sheet.GetRow(sheet.FirstRowNum);
                             for (int j = rowHead.FirstCellNum; j < rowHead.LastCellNum; j++)
                             {
                                 ICell cell = rowHead.GetCell(j);
                                 dt.Columns.Add(cell.StringCellValue);
                             }
                             ; j <= sheet.LastRowNum; j++)
                             {
                                 DataRow dr = dt.NewRow();
                                 IRow row = sheet.GetRow(j);
                                 for (int k = rowHead.FirstCellNum; k < rowHead.LastCellNum; k++)
                                 {
                                     dr[k] = row.GetCell(k).StringCellValue;
                                 }
                                 dt.Rows.Add(dr);
                             }
                             ds.Tables.Add(dt);
                         }
                     }
                     return ds;
                 }
             }
             catch (Exception ex)
             {
                 throw new Exception(ex.Message);
             }
         }
         #endregion Excel导出

         #region Excel导出

         /// <summary>
         /// Excel导出
         /// </summary>
         /// <param name="dt">虚拟表</param>
         /// <param name="fileName">文件路径</param>
         /// <param name="sheetName">Sheet路径为空请传null</param>
         /// <returns></returns>
         public static bool DataTableToXLS(DataTable dt, string fileName, string sheetName)
         {
             try
             {
                 if (dt == null)
                 {
                     return false;
                 }
                 if (String.IsNullOrEmpty(sheetName))
                 {
                     sheetName = Path.GetFileName(fileName);
                 }
                 var book = new NPOI.HSSF.UserModel.HSSFWorkbook();
                 book.CreateSheet();
                 var sheet = book.CreateSheet(sheetName);

                 IRow rowHead = sheet.CreateRow();
                 ; i < dt.Columns.Count; i++)
                 {
                     ICell cell = rowHead.CreateCell(i);
                     cell.SetCellValue(dt.Columns[i].ColumnName);
                 }
                 ; i < dt.Rows.Count; i++)
                 {
                     IRow row = sheet.CreateRow(i + );
                     ; j < dt.Columns.Count; j++)
                     {
                         ICell cell = row.CreateCell(j);
                         cell.SetCellValue(dt.Rows[i][j].ToString());
                     }
                 }

                 using (FileStream fsWriter = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Write))
                 {
                     book.Write(fsWriter);
                     return true;
                 }
             }
             catch (Exception ex)
             {
                 throw new Exception(ex.Message);
             }
         }

         /// <summary>
         /// DataSet 导出 到Excel
         /// </summary>
         /// <param name="ds">DataSet 表名默认为sheet名</param>
         /// <param name="fileName">文件路径</param>
         public static bool DataSetToExcel(DataSet ds, string fileName)
         {
             try
             {
                 String extension = Path.GetExtension(fileName).ToUpper();
                 IWorkbook book = null;
                 if (extension == ".XLS")
                 {
                     book = DataSetToHSSFWordbook(ds);
                 }
                 else if (extension == ".XLSX")
                 {
                     book = DataSetToXSSFWorkbook(ds);
                 }
                 else
                 {
                     throw new Exception("导入格式必须为xls或者xlsx");
                 }

                 using (FileStream fsWriter = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite))
                 {
                     book.Write(fsWriter);
                     return true;
                 }
             }
             catch (Exception ex)
             {
                 throw new Exception(ex.Message);
             }
         }
         /// <summary>
         /// DataSet 转换为 XSSFWorkbook 07
         /// </summary>
         /// <param name="ds"></param>
         /// <returns></returns>
         private static NPOI.XSSF.UserModel.XSSFWorkbook DataSetToXSSFWorkbook(DataSet ds)
         {
             try
             {
                 var book = new NPOI.XSSF.UserModel.XSSFWorkbook();
                 foreach (DataTable dt in ds.Tables)
                 {
                     ISheet sheet = book.CreateSheet(dt.TableName);
                     IRow rowHead = sheet.CreateRow();
                     ICellStyle style = book.CreateCellStyle();
                     style.BorderBottom = BorderStyle.Thin;
                     style.BorderTop = BorderStyle.Thin;
                     style.BorderLeft = BorderStyle.Thin;
                     style.BorderRight = BorderStyle.Thin;
                     IFont font = book.CreateFont();
                     font.FontHeightInPoints = ;
                     font.IsBold = true;
                     style.SetFont(font);
                     ; i < dt.Columns.Count; i++)
                     {
                         ICell cell = rowHead.CreateCell(i);
                         cell.CellStyle = style;
                         cell.SetCellValue(dt.Columns[i].ColumnName);
                     }
                     font.IsBold = false;
                     style.SetFont(font);
                     ; i < dt.Rows.Count; i++)
                     {
                         IRow row = sheet.CreateRow(i + );
                         DataRow dr = dt.Rows[i];
                         ; j < dt.Columns.Count; j++)
                         {
                             ICell cell = row.CreateCell(j);
                             cell.CellStyle = style;
                             cell.SetCellValue(dr[j].ToString());
                         }
                     }
                 }
                 return book;
             }
             catch (Exception ex)
             {
                 throw new Exception(ex.Message);
             }
         }

         /// <summary>
         /// DataSet 转换为 HSSFWorkbook 03
         /// </summary>
         /// <param name="ds"></param>
         /// <returns></returns>
         private static NPOI.HSSF.UserModel.HSSFWorkbook DataSetToHSSFWordbook(DataSet ds)
         {
             try
             {
                 var book = new NPOI.HSSF.UserModel.HSSFWorkbook();
                 var dsi = NPOI.HPSF.PropertySetFactory.CreateDocumentSummaryInformation();
                 dsi.Company = "xx软件股份有限公司";
                 var si = NPOI.HPSF.PropertySetFactory.CreateSummaryInformation();
                 si.Subject = "xx系统自动导出";
                 book.DocumentSummaryInformation = dsi;
                 book.SummaryInformation = si;

                 foreach (DataTable dt in ds.Tables)
                 {
                     ISheet sheet = book.CreateSheet(dt.TableName);
                     IRow rowHead = sheet.CreateRow();
                     ICellStyle style = book.CreateCellStyle();
                     style.BorderBottom = BorderStyle.Thin;
                     style.BorderTop = BorderStyle.Thin;
                     style.BorderLeft = BorderStyle.Thin;
                     style.BorderRight = BorderStyle.Thin;
                     IFont font = book.CreateFont();
                     font.FontHeightInPoints = ;
                     font.IsBold = true;
                     style.SetFont(font);
                     ; i < dt.Columns.Count; i++)
                     {
                         ICell cell = rowHead.CreateCell(i);
                         cell.CellStyle = style;
                         cell.SetCellValue(dt.Columns[i].ColumnName);
                     }
                     font.IsBold = false;
                     style.SetFont(font);
                     ; i < dt.Rows.Count; i++)
                     {
                         IRow row = sheet.CreateRow(i + );
                         DataRow dr = dt.Rows[i];
                         ; j < dt.Columns.Count; j++)
                         {
                             ICell cell = row.CreateCell(j);
                             cell.CellStyle = style;
                             cell.SetCellValue(dr[j].ToString());
                         }
                     }
                 }
                 return book;
             }
             catch (Exception ex)
             {
                 throw new Exception(ex.Message);
             }
         }

         #endregion
     }
 }

NPOI 导入导出excel 支持 03 07的更多相关文章

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

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

  2. NPOI导入导出Excel

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

  3. .Net core NPOI导入导出Excel

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

  4. Npoi导入导出Excel操作

    之前公司的一个物流商系统需要实现对订单的批量导入和导出,翻阅了一些资料,最后考虑使用NPOI实现这个需求. 在winform上面实现excel操作:http://www.cnblogs.com/Cal ...

  5. Excel操作--使用NPOI导入导出Excel为DataTable

    1.ExcelHelper封装 namespace NPOI操作Excel { public class ExcelHelper { /// <summary> /// DataTable ...

  6. NPOI导入导出EXCEL通用类,可直接使用在WinForm项目中

    由于XSSFWorkbook类型的Write方法限制,Write完成后就自动关闭流数据,所以无法很好的支持的Web模式,网上目前也未找到好的解决方案. 注意:若直接使用在WinForm项目中,必需先下 ...

  7. .net mvc利用NPOI导入导出excel

    1.导出Excel :首先引用NPOI包(Action一定要用FileResult) /// <summary> /// 批量导出需要导出的列表 /// </summary> ...

  8. ASP.Net MVC利用NPOI导入导出Excel

    因近期项目遇到所以记录一下: 首先导出Excel: 首先引用NPOI包 http://pan.baidu.com/s/1i3Fosux (Action一定要用FileResult) /// <s ...

  9. 使用NPOI导入导出Excel(xls/xlsx)数据到DataTable中

    using System; using System.Collections.Generic; using System.Text; using System.IO; using NPOI.SS.Us ...

随机推荐

  1. IOS判断设备是否已越狱

    转自:http://www.cnblogs.com/supercheng/archive/2012/12/05/2804166.html - (BOOL)isJailbroken { BOOL jai ...

  2. mysql中导入txt文件

    1 windows 下 mysql导入txt文件(使用mysql的workbench) load data local infile 'path' into table table_name fiel ...

  3. 【html】页面制作规范文档

    每天都在写html/css/js代码,总结的一些页面制作的规范 文件命名规范 1) 文件目录.文件名称统一用小写的英文字母.数字.下划线组合,文件名要与表现的内容相近,不到万不得已不要以拼音作为名称, ...

  4. php的ob_flush和flush(转)

    php.ini中 output_buffering = off 关闭php的缓存 implicit_flush = Off php不会立即输出到浏览器.如果是ON,相当于每次ECHO 立刻执行一个FL ...

  5. paip.sql2k,sql2005,sql2008,sql2008 r2,SQL2012以及EXPRESS版本的区别

    paip.sql2k,sql2005,sql2008,sql2008 r2,SQL2012以及EXPRESS版本的区别 作者Attilax ,  EMAIL:1466519819@qq.com  来源 ...

  6. ExpandoObject,DynamicObject,DynamicMetaObject

    ExpandoObject,DynamicObject,DynamicMetaObject 接上文:浅谈Dynamic关键字系列之三(上) 为什么TryXXX方法没有被调用?? 将DynamicPro ...

  7. 学习day01

    1.web C/S:Client Server 客户端 服务器 QQ,... B/S:Browser Server 浏览器 服务器 PC机:Personal Computer 个人电脑 2.HTML ...

  8. haroopad 預覽區樣式

    body { color:red; font-family:'Microsoft YaHei'; } html,body{ font-family: "微軟雅黑" !importa ...

  9. 第五章 绘图基础(ALTWIND)

    线上箭头表示画线的方向.WINDING模式和ALTERNATE模式都会填充三个封闭的L型区域,号码从1到3.两个更小的内部区域,号码为4和5,在ALTERNATE模式下不被填充.但是在WINDING模 ...

  10. vue中的路由高亮