//基本NPOI 1.2.5.0
static void Main(string[] args)
{
string path = string.Format("E:\\export{0}.xls", DateTime.Now.ToString("yyyyMMddhhmmss")); WriteAExcel(path);
ReadAExcel(path);
Console.ReadKey();
}
        /// <summary>
/// 创建测试
/// </summary>
/// <param name="path">路径</param>
static void WriteAExcel(string path)
{
//创建工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
//创建一个名称为"排班表"的表
ISheet sheet = workbook.CreateSheet("排班表"); int rowCount = ;
int colCount = ; //创建一行, 此行为标题行
IRow title = sheet.CreateRow(rowCount);
title.CreateCell().SetCellValue(string.Format("{0}({1})", "消化内科", "珠海市人民医院")); //合并单元格
CellRangeAddress cellRangeAddress = new CellRangeAddress(rowCount, rowCount, , colCount - );
sheet.AddMergedRegion(cellRangeAddress);
rowCount++; //创建一行, 空行
sheet.CreateRow(rowCount);
rowCount++; //创建一行,此行为第二行
IRow headerRow = sheet.CreateRow(rowCount);
rowCount++; //固定区域, 用于header
sheet.CreateFreezePane(, ); string[] headerArray = new[] { "医生", "日期", "时间", "预约数", "挂号费", "状态" }; //表头行
for (int i = ; i < headerArray.Length; i++)
{
headerRow.CreateCell(i).SetCellValue(headerArray[i]);
} List<MyDataItem> dataList = new List<MyDataItem>();
#region 测试数据
dataList.Add(new MyDataItem() { ID = , DoctorName = "张某", Date = DateTime.Now, Time = "上午", Place = , Fee = , Status = "排班" });
dataList.Add(new MyDataItem() { ID = , DoctorName = "李某", Date = DateTime.Now, Time = "下午", Place = , Fee = , Status = "排班" });
dataList.Add(new MyDataItem() { ID = , DoctorName = "赵某", Date = DateTime.Now, Time = "中午", Place = , Fee = , Status = "排班" });
dataList.Add(new MyDataItem() { ID = , DoctorName = "杨某", Date = DateTime.Now, Time = "上午", Place = , Fee = , Status = "停诊" });
dataList.Add(new MyDataItem() { ID = , DoctorName = "黎某", Date = DateTime.Now, Time = "中午", Place = , Fee = , Status = "排班" });
dataList.Add(new MyDataItem() { ID = , DoctorName = "张某", Date = DateTime.Now, Time = "上午", Place = , Fee = , Status = "排班" });
dataList.Add(new MyDataItem() { ID = , DoctorName = "李某", Date = DateTime.Now, Time = "下午", Place = , Fee = , Status = "排班" });
dataList.Add(new MyDataItem() { ID = , DoctorName = "赵某", Date = DateTime.Now, Time = "中午", Place = , Fee = , Status = "排班" });
dataList.Add(new MyDataItem() { ID = , DoctorName = "杨某", Date = DateTime.Now, Time = "上午", Place = , Fee = , Status = "停诊" });
dataList.Add(new MyDataItem() { ID = , DoctorName = "黎某", Date = DateTime.Now, Time = "中午", Place = , Fee = , Status = "排班" });
dataList.Add(new MyDataItem() { ID = , DoctorName = "张某", Date = DateTime.Now, Time = "上午", Place = , Fee = , Status = "排班" });
dataList.Add(new MyDataItem() { ID = , DoctorName = "李某", Date = DateTime.Now, Time = "下午", Place = , Fee = , Status = "排班" });
dataList.Add(new MyDataItem() { ID = , DoctorName = "赵某", Date = DateTime.Now, Time = "中午", Place = , Fee = , Status = "排班" });
dataList.Add(new MyDataItem() { ID = , DoctorName = "杨某", Date = DateTime.Now, Time = "上午", Place = , Fee = , Status = "停诊" });
dataList.Add(new MyDataItem() { ID = , DoctorName = "黎某", Date = DateTime.Now, Time = "中午", Place = , Fee = , Status = "排班" });
dataList.Add(new MyDataItem() { ID = , DoctorName = "张某", Date = DateTime.Now, Time = "上午", Place = , Fee = , Status = "排班" });
dataList.Add(new MyDataItem() { ID = , DoctorName = "李某", Date = DateTime.Now, Time = "下午", Place = , Fee = , Status = "排班" });
dataList.Add(new MyDataItem() { ID = , DoctorName = "赵某", Date = DateTime.Now, Time = "中午", Place = , Fee = , Status = "排班" });
dataList.Add(new MyDataItem() { ID = , DoctorName = "杨某", Date = DateTime.Now, Time = "上午", Place = , Fee = , Status = "停诊" });
dataList.Add(new MyDataItem() { ID = , DoctorName = "黎某", Date = DateTime.Now, Time = "中午", Place = , Fee = , Status = "排班" });
#endregion //添加下拉选项(序列)
AddDropdownList1(sheet, rowCount); //添加下拉选项(指定数据)
AddDropdownList2(workbook, sheet, rowCount); //插入数据
for (int i = ; i < dataList.Count; i++)
{
MyDataItem item = dataList[i];
IRow dataRow = sheet.CreateRow(rowCount); dataRow.CreateCell().SetCellValue(string.Format("{0}({1})", item.DoctorName, item.ID));
dataRow.CreateCell().SetCellValue(item.Date.ToString("yyyy/MM/dd"));
dataRow.CreateCell().SetCellValue(item.Time);
dataRow.CreateCell().SetCellValue(item.Place);
dataRow.CreateCell().SetCellValue(item.Fee.ToString("N2"));
dataRow.CreateCell();//.SetCellValue(item.Status);
rowCount++;
} //写入文件
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms); using (FileStream fs = new FileStream(path, FileMode.Create))
{
byte[] data = ms.ToArray();
fs.Write(data, , data.Count());
}
}
}
        //读测试
static void ReadAExcel(string path)
{
using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = new HSSFWorkbook(file);
ISheet sheet = workbook.GetSheet("排班表");
IRow headerRow = sheet.GetRow(); //一行最后一个方格的编号 即总的列数
int cellCount = headerRow.LastCellNum; //有多少列
int rowCount = sheet.LastRowNum; //读
for (int i = ; i < rowCount; i++)
{
IRow row = sheet.GetRow(i);
for (int j = row.FirstCellNum; j < cellCount; j++)
{
Console.Write(" " + row.GetCell(j).ToString());
}
Console.WriteLine();
}
}
}
        /// <summary>
/// 添加下拉框(序列)
/// </summary>
/// <param name="sheet"></param>
/// <param name="start"></param>
static void AddDropdownList1(ISheet sheet, int start)
{
CellRangeAddressList regions = new CellRangeAddressList(start, , , );
DVConstraint constraint = DVConstraint.CreateExplicitListConstraint(new string[] { "就诊", "停诊" });
HSSFDataValidation dataValidate = new HSSFDataValidation(regions, constraint);
sheet.AddValidationData(dataValidate);
} /// <summary>
/// 添加下拉框(单元格)
/// </summary>
/// <param name="workbook"></param>
/// <param name="sheet"></param>
/// <param name="start"></param>
static void AddDropdownList2(HSSFWorkbook workbook, ISheet sheet, int start)
{
ISheet sheet2 = workbook.CreateSheet("a");
sheet2.CreateRow().CreateCell().SetCellValue("上午");
sheet2.CreateRow().CreateCell().SetCellValue("中午");
sheet2.CreateRow().CreateCell().SetCellValue("下午");
sheet2.CreateRow().CreateCell().SetCellValue("晚上"); IName range = workbook.CreateName();
range.RefersToFormula = "a!$A$1:$A$4";
range.NameName = "timeDic"; CellRangeAddressList regions = new CellRangeAddressList(start, , , );
DVConstraint constraint = DVConstraint.CreateFormulaListConstraint("timeDic");
HSSFDataValidation dataValidate = new HSSFDataValidation(regions, constraint);
//添加约束警告
dataValidate.CreateErrorBox("输入不合法", "请输入下拉列表中的值。");
sheet.AddValidationData(dataValidate);
}
        /// <summary>
/// 测试数据类型
/// </summary>
class MyDataItem
{
public int ID { get; set; } public string DoctorName { get; set; } public DateTime Date { get; set; } public string Time { get; set; } public int Place { get; set; } public decimal Fee { get; set; } public string Status { get; set; }
}

备忘:

//2014/10/08

//加粗,15字
IFont Bold15Font = workbook.CreateFont();
Bold15Font.Boldweight = (short)FontBoldWeight.BOLD;
Bold15Font.FontHeightInPoints = ; //黄色底,横向居中,纵向居中,加粗,11字, 边框(单个)
ICellStyle YellowCenterBold11Cell = workbook.CreateCellStyle();
YellowCenterBold11Cell.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.YELLOW.index;
YellowCenterBold11Cell.FillPattern = FillPatternType.SOLID_FOREGROUND;
YellowCenterBold11Cell.Alignment = HorizontalAlignment.CENTER;
YellowCenterBold11Cell.VerticalAlignment = VerticalAlignment.CENTER;
YellowCenterBold11Cell.SetFont(Bold11Font);
YellowCenterBold11Cell.BorderBottom = BorderStyle.THIN;
YellowCenterBold11Cell.BorderLeft = BorderStyle.THIN;
YellowCenterBold11Cell.BorderRight = BorderStyle.THIN;
YellowCenterBold11Cell.BorderTop = BorderStyle.THIN; //给合并单元格加边框
CellRangeAddress cellRangeAddress0 = new CellRangeAddress(, , , );
sheet.AddMergedRegion(cellRangeAddress0);
((HSSFSheet)sheet).SetEnclosedBorderOfRegion(cellRangeAddress0, BorderStyle.THIN, NPOI.HSSF.Util.HSSFColor.BLACK.index); //单元格宽
sheet.SetColumnWidth(, * ); //行高
row0.HeightInPoints = Height25;
//2014/10/09
ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
IRow row1 = sheet1.CreateRow();
ICell cel1 = row1.CreateCell();
ICell cel2 = row1.CreateCell();
ICellStyle unlocked = hssfworkbook.CreateCellStyle();
unlocked.IsLocked = false;
ICellStyle locked = hssfworkbook.CreateCellStyle();
locked.IsLocked = true;//确定当前单元格被设置保护
cel1.SetCellValue("没被锁定");
cel1.CellStyle = unlocked;
cel2.SetCellValue("被锁定");
cel2.CellStyle = locked;
sheet1.ProtectSheet("password");//设置密码保护
sheet1.AutoSizeColumn(i);//自动宽度(不支持中文)

自动宽度( 支持中文)

     /// <summary>
/// 自动宽度支持中文
/// </summary>
public static void AutoSizeColumnExtension(this ISheet sheet, int maxColumn)
{ for (int i = ; i < maxColumn; i++)
{
sheet.AutoSizeColumn(i);
} //获取当前列的宽度,然后对比本列的长度,取最大值
for (int columnNum = ; columnNum < maxColumn; columnNum++)
{
int columnWidth = sheet.GetColumnWidth(columnNum) / ;
for (int rowNum = ; rowNum <= sheet.LastRowNum; rowNum++)
{
IRow currentRow;
//当前行未被使用过
if (sheet.GetRow(rowNum) == null)
{
currentRow = sheet.CreateRow(rowNum);
}
else
{
currentRow = sheet.GetRow(rowNum);
} if (currentRow.GetCell(columnNum) != null)
{
ICell currentCell = currentRow.GetCell(columnNum);
int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
if (columnWidth < length)
{
columnWidth = length;
}
}
}
sheet.SetColumnWidth(columnNum, (columnWidth > ? : columnWidth) * );
}
}

更多可以查看官方手册:http://tonyqus.sinaapp.com/

NPOI新建和读取EXCEL的更多相关文章

  1. 使用NPOI导出,读取EXCEL(可追加功能)

    使用NPOI导出,读取EXCEL,具有可追加功能 看代码 using System; using System.Collections.Generic; using System.Text; usin ...

  2. 使用net core 6 c# 的 NPOI 包,读取excel..xlsx单元格内的图片,并存储到指定服务器

    这个是记录,单元格的图片. 直接上代码,直接新建一个 net core api 解决方案,引用一下nuget包.本地创建一个 .xlsx 格式的excel文件 using ICSharpCode.Sh ...

  3. 使用NPOI读取Excel到DataTable

    一.NPOI介绍: 使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写.NPOI是构建在POI 3.x版本之上的,它可以在没有安装Office ...

  4. 【转】ExcelHelper类,用npoi读取Excel文档

    //------------------------------------------------------------------------------------- // All Right ...

  5. NPOI通过DataTable导出和读取Excel

    Excel导入及导出问题产生: 从接触.net到现在一直在维护一个DataTable导出到Excel的类,时不时还会维护一个导入类.以下是时不时就会出现的问题: 导出问题: 如果是asp.net,你得 ...

  6. NPOI 2.1.1 系列(1) 使用NPOI读取 Excel文档 ;NpoiExcelHelper 导入导出 2003格式 2007格式的 Excel; Npoi 导出 xlsx 格式

    下载地址 http://npoi.codeplex.com/releases 下面放一个 NPOIHelper 助手类吧,也不是我写的- NpoiExcelHelper 可以生成xlsx格式publi ...

  7. 使用NPOI读取Excel出错

    使用NPOI读取Excel出错,错误信息:java.io.IOException: Invalid header signature; read 4503608217567241, expected ...

  8. 使用NPOI读取Excel报错ICSharpCode.SharpZipLib.Zip.ZipException:Wrong Local header signature

    写了一个小程序利用NPOI来读取Excel,弹出这样的报错: ICSharpCode.SharpZipLib.Zip.ZipException:Wrong Local header signature ...

  9. NPOI读取Excel帮助类,支持xls与xlsx,实现公式解析,空行的处理

    NPOI读取Excel(2003或者2010)返回DataTable.支持公式解析,空行处理. /// <summary>读取excel /// 默认第一行为表头 /// </sum ...

随机推荐

  1. jquery selector

    jquery的选择器功能 1 :lt(index) selector 一组元素选择index之前的元素,若index<0 则倒着选过来 http://api.jquery.com/lt-sele ...

  2. 基于avalon1.4.x ----分页组件编写

    avalon分页组件 (1.4.x版本) 随着avalon2的推出,avalon1的官网已经不再维护了,现在似乎是找不到avalon 1.4版本的官方文档了,所以本文章所有的内容均不保证正确性,只能保 ...

  3. asp.net 内部重定向

    1. /* * 2. * Context.RewritePath() * 使用给定路径重写 URL.(内部重写) * 内部请求重写 */ public static void TestTwo() { ...

  4. 微软TTS,Neospeech TTS 简单使用

    今天搞了下微软的TTS,逛了好多网页.博客,拼拼凑凑搞了点东西吧. 首先添加类库调用,系统自带的system.speech using System.Speech.Synthesis; 然后就能调用方 ...

  5. Common Table Expressions (CTE)

    子查询有时使用起来很麻烦,因为所有的过滤和匹配逻辑都必须集成到子查询表达式中.如果只需要执行一个任务,且只需要使用一次杳询表达式,子查询是很好的选择.但子查询不能被重用,也不能很好地支持多个需求.这个 ...

  6. ios开发 block语句块

    ios开发 block语句块 1.block 理解为匿名函数 2.block变量的定义 //定义block变量,^表示定义block //技巧:函数名左右加括号,在函数名前面在加^ void (^bl ...

  7. JS闭包(一)

    闭包是指有权访问另一个函数作用域中的变量的函数. 创建闭包的常见方法:在一个函数内部创建另一个函数. 对彻底理解闭包,需要知道如何创建作用域链以及作用域链有什么作用的细节. 闭包的功能: 保存函数执行 ...

  8. react基于webpack和babel以及es6的项目搭建

    项目demo地址https://github.com/aushion/webpack_reac_config 1.打开命令提示窗口,输入 mkdir react_test cd react_test ...

  9. (转)Source vs Binary Disadvantages & Advantages of each!

    原链接:http://www.linuxforums.org/forum/newbie/26472-source-vs-binary-disadvantages-advantages-each.htm ...

  10. 【设计模式:单例模式】使用单例模式加载properties文件

    先准备测试程序: package org.jediael.util; import static org.junit.Assert.*; import org.junit.Test; public c ...