1、前言:

最近公司项目都用上了数据库,都要求具有报表的功能,需要导出Execl文件,或则使用Execl表导入相关的数据。于是查看资料发现很多都是使用微软提供的office COM组件,于是尝试了下,发现在一台电脑调试好了,然后在别的电脑上有容易出问题,后来总结出问题,发现是由于不同电脑安装的office 版本存在差异,所有,容易引起异常。

后来,在学习JAVA web的时候,发现在java web 中存在非常好用的一个开源项目POI,其实现脱离office 不同版本之间的差异性,后来百度查阅相关资料后发现,在C# 中也存在对应的NPOI。于是,记录下。

2、POI 和 NPOI

Apache POI是Apache软件基金会的开源项目,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。 .NET的开发人员则可以利用NPOI (POI for .NET) 来存取 Microsoft Office文档的功能。

 private void LoadingThread(){lock (mLockObject){mIsLoading = true;}DataTable dt = ExcelToDataTable("LoostCardUID", true);if (dt == null){return;}ShowRecord(dt);WriteLogcat("导入数据完成 ...", 0);lock (mLockObject){mIsLoading = false;}}
private string fileName = null; //文件名private IWorkbook workbook = null;private FileStream fs = null;/// <summary>/// 将excel中的数据导入到DataTable中/// </summary>/// <param name="sheetName">excel工作薄sheet的名称</param>/// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>/// <returns>返回的DataTable</returns>public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn){ISheet sheet = null;DataTable data = new DataTable();int startRow = 0;try{fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);if (fileName.IndexOf(".xlsx") > 0) // 2007版本workbook = new XSSFWorkbook(fs);else if (fileName.IndexOf(".xls") > 0) // 2003版本workbook = new HSSFWorkbook(fs);if (sheetName != null){sheet = workbook.GetSheet(sheetName);if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet{//sheet = workbook.GetSheetAt(0);MessageBox.Show("未找到正确的Execl表格文件!");return null;}}else{sheet = workbook.GetSheetAt(0);}if (sheet != null){IRow firstRow = sheet.GetRow(0);int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数if (isFirstRowColumn){for (int i = firstRow.FirstCellNum; i < cellCount; ++i){ICell cell = firstRow.GetCell(i);if (cell != null){cell.SetCellType(CellType.String);string cellValue = cell.StringCellValue;if (cellValue != null){DataColumn column = new DataColumn(cellValue);data.Columns.Add(column);}}}startRow = sheet.FirstRowNum + 1;}else{startRow = sheet.FirstRowNum;}//最后一列的标号int rowCount = sheet.LastRowNum;for (int i = startRow; i <= rowCount; ++i){IRow row = sheet.GetRow(i);if (row == null) continue; //没有数据的行默认是null       DataRow dataRow = data.NewRow();for (int j = row.FirstCellNum; j < cellCount; ++j){if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null{row.GetCell(j).SetCellType(CellType.String);dataRow[j] = row.GetCell(j).ToString();}}data.Rows.Add(dataRow);}}return data;}catch (Exception ex){MessageBox.Show(ex.Message);return null;}}
 /// <summary>/// Datable导出成Excel/// </summary>/// <param name="dt"></param>/// <param name="file">导出路径(包括文件名与扩展名)</param>public void TableToExcel(DataTable dt, string file, int type){HSSFWorkbook workbook;string fileExt = Path.GetExtension(file).ToLower();if (fileExt == ".xls"){workbook = new HSSFWorkbook();}else{workbook = null;}if (workbook == null){return;}ISheet sheet = workbook.CreateSheet("激活卡发卡记录");ICellStyle style = workbook.CreateCellStyle();ICellStyle dataStyle = workbook.CreateCellStyle();ICellStyle dataStyle2 = workbook.CreateCellStyle();HSSFPalette palette = workbook.GetCustomPalette();  //调色板实例palette.SetColorAtIndex(8, 200, 235, 253);palette.SetColorAtIndex(9, 255, 250, 239);palette.SetColorAtIndex(10, 236, 249, 255);HSSFColor hssFColorTitle = palette.FindColor(200, 235, 253);HSSFColor hssFColorData = palette.FindColor(255, 250, 239);HSSFColor hssFColorData2 = palette.FindColor(236, 249, 255);style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;style.WrapText = true;style.FillForegroundColor = hssFColorTitle.Indexed;style.FillPattern = FillPattern.SolidForeground;style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;style.BottomBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;style.LeftBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;style.RightBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;style.TopBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;dataStyle.WrapText = true;dataStyle.FillForegroundColor = hssFColorData.Indexed;dataStyle.FillPattern = FillPattern.SolidForeground;dataStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;dataStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;dataStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;dataStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;dataStyle.BottomBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;dataStyle.LeftBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;dataStyle.RightBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;dataStyle.TopBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;dataStyle2.WrapText = true;dataStyle2.FillForegroundColor = hssFColorData2.Indexed;dataStyle2.FillPattern = FillPattern.SolidForeground;dataStyle2.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;dataStyle2.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;dataStyle2.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;dataStyle2.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;dataStyle2.BottomBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;dataStyle2.LeftBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;dataStyle2.RightBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;dataStyle2.TopBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;IFont font = workbook.CreateFont();IFont dataFont = workbook.CreateFont();font.FontHeightInPoints = 10;//font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;font.FontName = "微软雅黑";dataFont.FontHeightInPoints = 9;dataFont.FontName = "微软雅黑";style.SetFont(font);                //HEAD样式dataStyle.SetFont(dataFont);        //数据样式dataStyle2.SetFont(dataFont);        //数据样式//表头  IRow row = sheet.CreateRow(0);                              //创建第一行,表头ICell cell = row.CreateCell(0);                         //写列      cell.SetCellValue("序号");cell.CellStyle = style;sheet.SetColumnWidth(0, 10 * 256);cell = row.CreateCell(1);                         //写列      cell.SetCellValue("公司名");cell.CellStyle = style;sheet.SetColumnWidth(1, 40 * 256);cell = row.CreateCell(2);                         //写列      cell.SetCellValue("注册码");cell.CellStyle = style;sheet.SetColumnWidth(2, 50 * 256);cell = row.CreateCell(3);                         //写列      cell.SetCellValue("激活码");cell.CellStyle = style;sheet.SetColumnWidth(3, 50 * 256);cell = row.CreateCell(4);                         //写列      cell.SetCellValue("有效期");cell.CellStyle = style;sheet.SetColumnWidth(4, 25 * 256);cell = row.CreateCell(5);                         //写列      cell.SetCellValue("时间");cell.CellStyle = style;sheet.SetColumnWidth(5, 25 * 256);//数据  if (type == 1){//导出所有if (dt != null && dt.Rows.Count != 0){for (int ik = 0; ik < dt.Rows.Count; ik++){IRow row1 = sheet.CreateRow(ik + 1);                     //创建第二行cell = row1.CreateCell(0);                         //写列      cell.SetCellValue((ik + 1).ToString());cell.CellStyle = dataStyle;sheet.SetColumnWidth(0, 10 * 256);cell = row1.CreateCell(1);                         //写列      cell.SetCellValue(dt.Rows[ik][1].ToString());cell.CellStyle = dataStyle2;sheet.SetColumnWidth(1, 40 * 256);cell = row1.CreateCell(2);                         //写列      cell.SetCellValue(dt.Rows[ik][2].ToString());cell.CellStyle = dataStyle;sheet.SetColumnWidth(2, 50 * 256);cell = row1.CreateCell(3);                         //写列      cell.SetCellValue(dt.Rows[ik][3].ToString());cell.CellStyle = dataStyle2;sheet.SetColumnWidth(3, 50 * 256);cell = row1.CreateCell(4);                         //写列      cell.SetCellValue(dt.Rows[ik][4].ToString());cell.CellStyle = dataStyle;sheet.SetColumnWidth(4, 25 * 256);cell = row1.CreateCell(5);                         //写列      cell.SetCellValue(dt.Rows[ik][5].ToString());cell.CellStyle = dataStyle2;sheet.SetColumnWidth(5, 25 * 256);}}}else{//导出当前列表for (int ik = 0; ik < mList.Count; ik++){IRow row1 = sheet.CreateRow(ik + 1);                     //创建第二行cell = row1.CreateCell(0);cell.SetCellValue((ik + 1).ToString());cell.CellStyle = dataStyle;sheet.SetColumnWidth(0, 10 * 256);cell = row1.CreateCell(1);                         //写列      cell.SetCellValue(mList[ik].getName());cell.CellStyle = dataStyle2;sheet.SetColumnWidth(1, 40 * 256);cell = row1.CreateCell(2);                         //写列      cell.SetCellValue(mList[ik].getRegistercode());cell.CellStyle = dataStyle;sheet.SetColumnWidth(2, 50 * 256);cell = row1.CreateCell(3);                         //写列      cell.SetCellValue(mList[ik].getActivecode());cell.CellStyle = dataStyle2;sheet.SetColumnWidth(3, 50 * 256);cell = row1.CreateCell(4);                         //写列      cell.SetCellValue(mList[ik].getTime());cell.CellStyle = dataStyle;sheet.SetColumnWidth(4, 25 * 256);cell = row1.CreateCell(5);                         //写列      cell.SetCellValue(mList[ik].getValiditytime());cell.CellStyle = dataStyle2;sheet.SetColumnWidth(5, 25 * 256);}}try{//转为字节数组  MemoryStream stream = new MemoryStream();workbook.Write(stream);var buf = stream.ToArray();//保存为Excel文件  using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write)){fs.Write(buf, 0, buf.Length);fs.Flush();}}catch (Exception e1){LogcatService.WriteLogcat(e1);ShowMessage(0, "导出Execl 文件失败");return;}ShowMessage(1, "导出Execl 文件成功");}

这里只记录使用的部分,其他的可以百度查阅相关的资料。

C# 使用NPIO 导出导出EXECL相关推荐

  1. asp.net C# 将数据导出到Execl汇总

    asp.net中导出Execl的方法: 在asp.net中导出Execl有两种方法,一种是将导出的文件存放在服务器某个文件夹下面,然后将文件地址输出在浏览器上:一种是将文件直接将文件输出流写给浏览器. ...

  2. Z05 - 044、Sqoop 导出 - 导出 HDFS 数据到 MySQL

    初学耗时:0.5h 注:CSDN手机端暂不支持章节内链跳转,但外链可用,更好体验还请上电脑端. 一.Sqoop 导出 - 导出 HDFS 数据到 mysql 记忆词:   导出 HDFS 数据到 My ...

  3. MySQL 使用命令行导出导出数据库、数据表、表结构

    简单粗暴 ⛽️ 导入 导入前必读 导入之前目标数据库必须存在 常用 source 命令导入 导入数据库 # 1. 连接数据库 mysql -h 主机地址 -u 用户名 -p 按回车# 2. 输入密码, ...

  4. 2003服务器导出配置文件,Windows Server 导出/导出IIS配置方法

    Windows 2003 导出/导出IIS配置操作步骤 1.首先登陆服务器,打开internet信息服务(IIS)管理器,在[IIS信息服务管理器]-[本地计算机],右键选择所有任务-备份/还原配置. ...

  5. winform使用NPIO导入导出Excel

    安装包NPIO 命名空间 using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System.IO; 界面 导出 /// <summ ...

  6. Execl模板导出复杂Execl文件

    需求: 根据Execl模板文件导出Execl,填充红色框框部分.如下图: 资料参考位置:Java实现根据excel模板导出数据(适合导出结构复杂的excel)_名字看着办的博客-CSDN博客_java ...

  7. idea将java导出word文档,Java导出word/execl文档

    使用FreeMarker的模板技术快速实现动态生成word 实现思路是这样的:先创建一个word文档,按照需求在word中填好一个模板,然后把对应的数据换成变量${},然后将文档保存为xml文档格式, ...

  8. 【MATLAB】图像导出 ( 导出绘制的图像 | 图像设置 )

    文章目录 一.导出图像 1.生成的图像 2.复制图形 3.保存 4.另存为 二.复制选项 1.复制选项 2.图形属性 3.导出设置 一.导出图像 1.生成的图像 2.复制图形 选择 matlab 生成 ...

  9. jspdf 分页_使用html2canvas跟jspdf导出导出PDF文件

    前言:最近项目中有将html文件导出PDF需求,了解网上有jspdf,whtmltopdf等方法. 由于whtmltopdf需要在服务端安装whtmltopdf,为了简便,选择了js方法. 需要插件: ...

  10. Oracle常用导出导出命令及性能效率对比

    说明 Oracle导入导出命令主要有EXPDP和IMPDP.EXP和IMP,区别如下:EXP和IMP是客户端工具程序,它们既可以在客户端使用,也可以在服务端使用.EXPDP和IMPDP是服务端的工具程 ...

最新文章

  1. 剑指offer:面试题22. 链表中倒数第k个节点
  2. Android小项目之---选择对话框(附源码)
  3. 【Unity3D自学记录】判断物体是否在镜头内
  4. border和图片之间有缝隙_院子里现浇水泥板,每块之间留7公分的缝,铺出来的效果漂亮大气...
  5. 浅谈MySQL的B树索引与索引优化
  6. 多方法接口回调_啊?Java反射遇到接口
  7. lightoj1145 【DP优化求方案】
  8. termcap-1.3.1的configure.in文件逐行分析
  9. 31 SD配置-主数据-信用管理-定义自动信贷控制
  10. 在Vim中将DOS行尾转换为Linux行尾
  11. MapReduce框架Hadoop应用(一)
  12. RGB YUV XYZ HSL CIE1976L*a*b* LCH的色彩空间图 色彩空间 转换公式
  13. 《知识就是力量》第二期——“怎样做一个更有价值的人”笔记
  14. Mac上键入数学符号怎样输入
  15. win下海康工业相机使用python读取视频并转换成cv格式
  16. google glog使用指南
  17. SpringBoot国际化配置
  18. 巴黎圣母院重建设计竞赛辟谣!“巴黎心跳”夺冠,仅仅只是自嗨?
  19. python爬取考研成绩什么时候出来_Python 爬取揭秘,你的考研调剂对手就有谁?...
  20. 触摸传感器PCB布局设计指南(二)

热门文章

  1. 想买云服务器,有性能比较好的推荐吗?
  2. 小程序开发商可以在哪里接项目订单/有几种接单方式
  3. c语言求开平方标准库函数,c语言如何求平方根 C语言中开平方函数是什么?
  4. 操作WORD文件:使用MSWORD.OLB组件将RichTextBox中的文本保存为WORD格式文件。
  5. 模拟电子_热敏电阻PTC和NTC的区别与作用
  6. hp打印机计算机接口,老司机操作电脑连接惠普打印机提示无法识别UsB端口的办法?...
  7. 1055 集体照 (25 分)
  8. jmeter ramup设置_Jmeter(2)基础知识
  9. Intel CPU发展史
  10. 【地理坐标系、大地坐标系与地图投影与重投影详解】