NPOI版本:2.5.1.0

ICSharpCode.SharpZipLib版本:1.2.0.246

.NET:4.5

using System;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;
using System.Collections.Generic;
using NPOI.SS.Util;
using System.Text;namespace MapExcelNpoi01
{/// <summary>/// NPOIExcel 针对2.5.1.0出的NPOI操作Excel类的常用方法;/// </summary>public class NPOIExcel{/// <summary>/// 记录打开的Excel的路径/// </summary>private string npoiFileName;/// <summary>/// 工作簿,全局变量/// </summary>protected IWorkbook workbook;/// <summary>/// 获取工作表或是创建的/// </summary>private NPOI.SS.UserModel.ISheet sheet;/// <summary>/// 构造方法/// </summary>public NPOIExcel(){npoiFileName = "";workbook = new XSSFWorkbook();}/// <summary>/// 打开/// </summary>/// <param name="filename">excel文件路径</param>public void Open(string filename){using (FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read)){string ext = Path.GetExtension(filename).ToLower();if (ext == ".xlsx")workbook = new XSSFWorkbook(fileStream);else{workbook = new HSSFWorkbook(fileStream);}}npoiFileName = filename;}/// <summary>/// 创建一个Excel对象,该对象为可见的/// </summary>public void Create(string sheetname = "Sheet1"){sheet = workbook.CreateSheet(sheetname);}/// <summary>/// 获取一个工作表/// </summary>/// <param name="SheetName">工作表名称</param>/// <returns></returns>public ISheet GetSheet(string SheetName){return (sheet = workbook.GetSheet(SheetName) ?? workbook.CreateSheet(SheetName));}/// <summary>/// 添加一个工作表/// </summary>/// <param name="SheetName">工作表名称</param>/// <returns></returns>public ISheet AddSheet(string SheetName){ISheet s = workbook.CreateSheet(SheetName);return s;}/// <summary>/// 删除一个工作表/// </summary>/// <param name="SheetName">工作表名称</param>public void DelSheet(string SheetName){int index = workbook.GetNameIndex(SheetName);workbook.RemoveSheetAt(index);}/// <summary>/// 重命名一个工作表/// </summary>/// <param name="OldSheetName">老工作表名称</param>/// <param name="NewSheetName">新工作表名称</param>/// <returns></returns>public ISheet ReNameSheet(string OldSheetName, string NewSheetName){int index = workbook.GetNameIndex(OldSheetName);workbook.SetSheetName(index, NewSheetName);return workbook.GetSheetAt(index);}/// <summary>/// 设置单元格的值/// </summary>/// <param name="sheetName">工作表名称</param>/// <param name="row">行</param>/// <param name="col">列</param>/// <param name="value">设置的值</param>private void SetCellValue(ISheet sheetName, int row, int col, object value){IRow _row = sheetName.GetRow(row) ?? sheetName.CreateRow(row);ICell cell = _row.GetCell(col) ?? _row.CreateCell(col);string valuetype = value.GetType().Name.ToLower();switch (valuetype){case "string"://字符串类型   case "system.string":case "datetime":case "system.datetime"://日期类型  case "boolean"://布尔型   case "system.boolean"://布尔型    cell.SetCellType(CellType.String);cell.SetCellValue(value.ToString());break;case "byte":case "int":case "int16":case "int32":case "int64":case "system.int16"://整型   case "system.int32":case "system.int64":case "system.byte":cell.SetCellType(CellType.Numeric);cell.SetCellValue(Convert.ToInt32(value));break;case "single":case "system.single":case "double":case "system.double":case "decimal":case "system.decimal":cell.SetCellType(CellType.Numeric);cell.SetCellValue(Convert.ToDouble(value));break;case "dbnull"://空值处理   case "system.dbnull"://空值处理   cell.SetCellValue("");break;default:cell.SetCellValue(value.ToString());break;}}/// <summary>/// 要设值的工作表的名称 X行Y列 value 值/// </summary>/// <param name="sheetName">工作表名</param>/// <param name="row">行</param>/// <param name="col">列</param>/// <param name="value">插入的值</param>public void SetCellValue(string sheetName, int row, int col, object value){ISheet s = GetSheet(sheetName);SetCellValue(s, row, col, value);}/// <summary>/// 获取单元格值/// </summary>/// <param name="sheetName">工作表名</param>/// <param name="row">行</param>/// <param name="col">列</param>/// <returns></returns>public ICell GetCell(string sheetName, int row, int col){return GetSheet(sheetName).GetRow(row).Cells[col];}/// <summary>/// 获取单元格值/// </summary>/// <param name="sheetName">工作表名</param>/// <param name="row">行</param>/// <param name="col">列</param>/// <returns></returns>private ICell GetCell(ISheet sheetName, int row, int col){//return ws.GetRow(row).Cells[col];return sheetName.GetRow(row).GetCell(col);}/// <summary>/// 设置单元格的属性(字体,大小,颜色,对齐方式)(前提是该行列范围内有值,否则报错)/// </summary>/// <param name="sheetName"></param>/// <param name="startRow">起始行</param>/// <param name="startCol">起始列</param>/// <param name="endRow">结束行</param>/// <param name="endCol">结束列</param>/// <param name="fontName">字体</param>/// <param name="indexedColors">字体颜色</param>/// <param name="fontSize">字体大小</param>/// <param name="horizontalAlignment">水平排列</param>public void SetCellProperty(string sheetName, int startRow, int startCol, int endRow, int endCol, string fontName, IndexedColors indexedColors, int fontSize, HorizontalAlignment horizontalAlignment){SetCellProperty(GetSheet(sheetName), startRow, startCol, endRow, endCol, fontName, indexedColors, fontSize, horizontalAlignment);}/// <summary>/// 设置一个单元格的属性(字体,大小,颜色,对齐方式)/// </summary>/// <param name="sheetName"></param>/// <param name="Startx"></param>/// <param name="Starty"></param>/// <param name="Endx"></param>/// <param name="Endy"></param>/// <param name="fontName"></param>/// <param name="indexedColors"></param>/// <param name="fontSize"></param>/// <param name="horizontalAlignment"></param>private void SetCellProperty(ISheet sheetName, int startRow, int startCol, int endRow, int endCol, string fontName, IndexedColors indexedColors, int fontSize, HorizontalAlignment horizontalAlignment){ICellStyle style = workbook.CreateCellStyle();IFont font = workbook.CreateFont();font.Color = indexedColors.Index;font.FontName = fontName;font.FontHeightInPoints = fontSize;//font.Boldweight = Boldweight;//字体加粗style.Alignment = horizontalAlignment;//style.VerticalAlignment = VerticalAlignment.Center; //垂直居中style.SetFont(font);foreach (ICell cell in GetCellsOfRange(sheetName, startRow, startCol, endRow, endCol)){cell.CellStyle = style;}}/// <summary>/// 获取起止范围内的行列值/// </summary>/// <param name="sheetName"></param>/// <param name="startRow"></param>/// <param name="startCol"></param>/// <param name="endRow"></param>/// <param name="endCol"></param>/// <returns></returns>public IList<ICell> GetCellsOfRange(string sheetName, int startRow, int startCol, int endRow, int endCol){return (GetCellsOfRange(GetSheet(sheetName), startRow, startCol, endRow, endCol));}/// <summary>/// 获取起止范围内的行列值/// </summary>/// <param name="sheetName"></param>/// <param name="startRow"></param>/// <param name="startCol"></param>/// <param name="endRow"></param>/// <param name="endCol"></param>/// <returns></returns>private IList<ICell> GetCellsOfRange(ISheet sheetName, int startRow, int startCol, int endRow, int endCol){IList<ICell> allCell = new List<ICell>();for (int i = startRow; i <= endRow; i++)for (int j = startCol; j <= endCol; j++){allCell.Add(GetCell(sheetName, i, j));}return allCell;}/// <summary>/// 合并单元格/// </summary>/// <param name="sheetName"></param>/// <param name="startRow"></param>/// <param name="endRow"></param>/// <param name="startCol"></param>/// <param name="endCol"></param>private void MergedCells(ISheet sheetName, int startRow, int endRow, int startCol, int endCol){//CellRangeAddress四个参数为:起始行,结束行,起始列,结束列sheetName.AddMergedRegion(new CellRangeAddress(startRow, endRow, startCol, endCol));}/// <summary>/// 合并单元格/// </summary>/// <param name="sheetName"></param>/// <param name="startRow"></param>/// <param name="startCol"></param>/// <param name="endRow"></param>/// <param name="endCol"></param>public void MergedCells(string sheetName, int startRow, int startCol, int endRow, int endCol){MergedCells(GetSheet(sheetName), startRow, endRow, startCol, endCol);}/// <summary>/// 文档另存为/// </summary>/// <param name="FileName"></param>/// <returns></returns>public bool SaveAs(string FileName){npoiFileName = FileName;try{using (FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write)){workbook.Write(fs);}return true;}catch{return false;}}/// <summary>/// 关闭/// </summary>public void Close(){workbook.Close();}/// <summary>/// 自适应宽度/// </summary>/// <param name="sheetName">表名</param>/// <param name="startCol">起始列</param>/// <param name="endCol">结束列</param>public void AutoColumnWidth(string sheetName, int startCol, int endCol){AutoColumnWidth(GetSheet(sheetName), startCol, endCol);}/// <summary>/// 自适应宽度/// </summary>/// <param name="sheet"></param>/// <param name="cols"></param>private void AutoColumnWidth(ISheet sheet, int startCol, int endCol){for (int col = startCol; col <= endCol; col++){sheet.AutoSizeColumn(col);//但是其实还是比实际文本要宽}}/// <summary>/// 设置起止范围的行高,单位为磅/// </summary>/// <param name="sheetName">工作表名称</param>/// <param name="startRow">起始行</param>/// <param name="endRow">结束行</param>/// <param name="heightValue">设置的高值</param>public void SetRowsHeight(string sheetName, int startRow, int endRow, int heightValue){ISheet sheet = GetSheet(sheetName);for (int i = startRow; i <= endRow; i++){//sheet.GetRow(i).Height = Height * 20;sheet.GetRow(i).HeightInPoints = heightValue;}}/// <summary>/// 设置起止列的宽度,单位为字符/// </summary>/// <param name="sheetName">工作表名称</param>/// <param name="startCol">起始列</param>/// <param name="endCol">结束列</param>/// <param name="widthValue">设置的宽度值</param>public void SetColumnsWidth(string sheetName, int startCol, int endCol, int widthValue){ISheet sheet = GetSheet(sheetName);for (int j = startCol; j <= endCol; j++){sheet.SetColumnWidth(3, widthValue * 256);}}/// <summary>/// 插入新行/// </summary>/// <param name="sheetName">工作表名</param>/// <param name="insertRowIndex">插入的行索引位置</param>/// <param name="insertRowCount">插入的行数量</param>/// <param name="formatRowIndex">获取插入行的参照样式的行索引</param>public void InsertRow(string sheetName, int insertRowIndex, int insertRowCount, int formatRowIndex){ISheet sheet = GetSheet(sheetName);IRow formatRow = sheet.GetRow(formatRowIndex);InsertRow(sheet, insertRowIndex, insertRowCount, formatRow);}/// <summary>/// 插入新行/// </summary>/// <param name="sheetName"></param>/// <param name="insertRowIndex"></param>/// <param name="insertRowCount"></param>/// <param name="formatRow"></param>private void InsertRow(ISheet sheetName, int insertRowIndex, int insertRowCount, IRow formatRow){sheet.ShiftRows(insertRowIndex, sheet.LastRowNum, insertRowCount, true, false);for (int i = insertRowIndex; i < insertRowIndex + insertRowCount; i++){IRow targetRow = null;ICell sourceCell = null;ICell targetCell = null;targetRow = sheet.CreateRow(i);for (int m = formatRow.FirstCellNum; m < formatRow.LastCellNum; m++){sourceCell = formatRow.GetCell(m);if (sourceCell == null){continue;}targetCell = targetRow.CreateCell(m);targetCell.CellStyle = sourceCell.CellStyle;targetCell.SetCellType(sourceCell.CellType);}}for (int i = insertRowIndex; i < insertRowIndex + insertRowCount; i++){IRow firstTargetRow = sheet.GetRow(i);ICell firstSourceCell = null;ICell firstTargetCell = null;for (int m = formatRow.FirstCellNum; m < formatRow.LastCellNum; m++){firstSourceCell = formatRow.GetCell(m, MissingCellPolicy.CREATE_NULL_AS_BLANK);if (firstSourceCell == null){continue;}firstTargetCell = firstTargetRow.GetCell(m, MissingCellPolicy.CREATE_NULL_AS_BLANK);firstTargetCell.CellStyle = firstSourceCell.CellStyle;firstTargetCell.SetCellType(firstSourceCell.CellType);}}}}
}

NPOI操作Excel类代码(打开 插入 设置行列宽 合并单元格 增删改工作表 保存等等) .NET4.5相关推荐

  1. Java实战—POI操作Excel文档、读取、写入、合并单元格

    一.POI项目简介 POI全称 Poor Obfuscation Implementation,利用POI接口可以通过JAVA操作Microsoft office 套件工具的读写功能.官网:http: ...

  2. C# Excel 行高,列宽,合并单元格,单元格边框线,冻结

    C# Excel 行高,列宽,合并单元格,单元格边框线,冻结 原文:http://hi.baidu.com/kjkj911/blog/item/0ecc3ec7855dd6d4d100600f.htm ...

  3. python pptx 关于在ppt里插入表格,调整合并单元格的问题

    python pptx 关于在ppt里插入表格,调整合并单元格的问题 需求 找到合并了的单元格 思路 判断是否是合并单元格 合并位置的记录 合并 代码 需求 首先我这是为了从word里面将内容导到pp ...

  4. 学习Python处理Excel 难度1级别 多表合并、数据透视表、拆分合并单元格并获得一维表

    #本代码要点:多表合并.数据透视表.拆分合并单元格并获得一维表 #主题:各门店合并,计算各店当月回店做服务2次+的客人数量 #EXCEL工作表:存在合并单元格 #备注: import pandas a ...

  5. Speedoffice(word)插入表格,如何合并单元格?

    在用Word制作表格的时候,有时插入的表格需要合并单元格,那怎么合并了?以最常用的speedoffice为例和大家分享一下. 1,首先运行软件,新建一份word插入表格作为演示,接着选中需要合并的单元 ...

  6. PHPExcel导出Excel基本操作,实现设置字体、合并单元格、加粗等功能

    PHPExcel一些相关操作,只罗列了部分功能,后续有新增再补充.代码可直接复制使用,需要注意是引入PHPExcel类库时因为是thinkphp框架,所以使用了import导入,如果其他框架,需要做部 ...

  7. C# Excel 行高,列宽,合并单元格,单元格边框线,冻结(转载) - 关于C#操作EXCLE常见操作比较全的

    网上看到的比较全的关于C#操作EXCEL常见操作集合,比较全,写的不错 原文地址:http://hi.baidu.com/kjkj911/blog/item/0ecc3ec7855dd6d4d1006 ...

  8. poi操作excel,复制sheet,复制行,复制单元格

    项目中,我们经常使用Poi来操作excel,但是经常碰到一个不方便的地方,不如最简单常用的,在两个excel之间复制sheet,复制行,复制单元格等. 我这里是最近刚做的一个简单封装.不是很好,必须始 ...

  9. poi操作excel,复制sheet,复制行,复制单元格 .

    http://blog.csdn.net/wutbiao/article/details/8696446 项目中,我们经常使用Poi来操作excel,但是经常碰到一个不方便的地方,不如最简单常用的,在 ...

  10. javaweb使用poi下载excel设置样式、合并单元格、设置列宽

    @Overridepublic void exportMajorInfo(@RequestBody StudentInfoDto studentInfoDto) {// 至少存在4列int miniC ...

最新文章

  1. C/C++ 输出整数带正负号
  2. git 使用_Git使用总结
  3. junit 循环测试_重复运行JUnit测试而没有循环
  4. tb计算机存储单位_如何节省数TB的云存储
  5. 程序员的算法课(13)-分治法
  6. [转][C#] .net动态编译C# 和 VB
  7. 再见了,mover。当打之年,感恩相遇,感恩联汇,感恩一切。
  8. c语言异或 反汇编,[原创]qq反汇编日志(1,2,3,4)
  9. Bengio最新博文:深度学习展望
  10. 2021SC@SDUSC Zxing开源代码(十六)PDF417二维码(二)
  11. 读书笔记5.2——《让数字说话:审计,就这么简单》:孙含晖
  12. bmon 带宽监视器
  13. 计算机文字录入培训大纲,计算机文字录入处理员教学大纲.doc
  14. matplotlib 基础_子图创建
  15. 驱动力3.0,动力全开~
  16. 2020年中国功能性儿童学习用品行业白皮书
  17. JAVA学习笔记—IO流
  18. MTK6592平台 touchpanel驱动设备加载(一)
  19. 服务器修复 dns,AD 林恢复 - 配置 DNS 服务器服务
  20. 2017年计算机应用基础,计算机应用基础考试试题及答案

热门文章

  1. 梦幻西游脚本开发教学
  2. 详细图解,一眼就能看懂!卷帘快门(Rolling Shutter)与全局快门(Global Shutter)的区别
  3. 路由器的下一跳计算(网关)
  4. python绘制坐标系_借助Python Turtle,了解计算机绘图的坐标系
  5. MySQL自学笔记(三)
  6. Vuecli 城市三级联动的使用
  7. 算法训练 递归输出数字三角形
  8. python获取本机IP地址
  9. 深度学习-浅层神经网络
  10. VBV大小-H.264