NPOI新建和读取EXCEL

        //基本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 = 0;
            int colCount = 6;

            //创建一行, 此行为标题行
            IRow title = sheet.CreateRow(rowCount);
            title.CreateCell(0).SetCellValue(string.Format("{0}({1})", "消化内科", "珠海市人民医院"));

            //合并单元格
            CellRangeAddress cellRangeAddress = new CellRangeAddress(rowCount, rowCount, 0, colCount - 1);
            sheet.AddMergedRegion(cellRangeAddress);
            rowCount++;

            //创建一行, 空行
            sheet.CreateRow(rowCount);
            rowCount++;

            //创建一行,此行为第二行
            IRow headerRow = sheet.CreateRow(rowCount);
            rowCount++;

            //固定区域, 用于header
            sheet.CreateFreezePane(0, 1);

            string[] headerArray = new[] { "医生", "日期", "时间", "预约数", "挂号费", "状态" };

            //表头行
            for (int i = 0; i < headerArray.Length; i++)
            {
                headerRow.CreateCell(i).SetCellValue(headerArray[i]);
            }

            List<MyDataItem> dataList = new List<MyDataItem>();
            #region 测试数据
            dataList.Add(new MyDataItem() { ID = 1, DoctorName = "张某", Date = DateTime.Now, Time = "上午", Place = 3, Fee = 10, Status = "排班" });
            dataList.Add(new MyDataItem() { ID = 2, DoctorName = "李某", Date = DateTime.Now, Time = "下午", Place = 3, Fee = 10, Status = "排班" });
            dataList.Add(new MyDataItem() { ID = 3, DoctorName = "赵某", Date = DateTime.Now, Time = "中午", Place = 3, Fee = 10, Status = "排班" });
            dataList.Add(new MyDataItem() { ID = 4, DoctorName = "杨某", Date = DateTime.Now, Time = "上午", Place = 3, Fee = 10, Status = "停诊" });
            dataList.Add(new MyDataItem() { ID = 5, DoctorName = "黎某", Date = DateTime.Now, Time = "中午", Place = 3, Fee = 10, Status = "排班" });
            dataList.Add(new MyDataItem() { ID = 6, DoctorName = "张某", Date = DateTime.Now, Time = "上午", Place = 3, Fee = 10, Status = "排班" });
            dataList.Add(new MyDataItem() { ID = 7, DoctorName = "李某", Date = DateTime.Now, Time = "下午", Place = 3, Fee = 10, Status = "排班" });
            dataList.Add(new MyDataItem() { ID = 8, DoctorName = "赵某", Date = DateTime.Now, Time = "中午", Place = 3, Fee = 10, Status = "排班" });
            dataList.Add(new MyDataItem() { ID = 9, DoctorName = "杨某", Date = DateTime.Now, Time = "上午", Place = 3, Fee = 10, Status = "停诊" });
            dataList.Add(new MyDataItem() { ID = 10, DoctorName = "黎某", Date = DateTime.Now, Time = "中午", Place = 3, Fee = 10, Status = "排班" });
            dataList.Add(new MyDataItem() { ID = 11, DoctorName = "张某", Date = DateTime.Now, Time = "上午", Place = 3, Fee = 10, Status = "排班" });
            dataList.Add(new MyDataItem() { ID = 12, DoctorName = "李某", Date = DateTime.Now, Time = "下午", Place = 3, Fee = 10, Status = "排班" });
            dataList.Add(new MyDataItem() { ID = 13, DoctorName = "赵某", Date = DateTime.Now, Time = "中午", Place = 3, Fee = 10, Status = "排班" });
            dataList.Add(new MyDataItem() { ID = 14, DoctorName = "杨某", Date = DateTime.Now, Time = "上午", Place = 3, Fee = 10, Status = "停诊" });
            dataList.Add(new MyDataItem() { ID = 15, DoctorName = "黎某", Date = DateTime.Now, Time = "中午", Place = 3, Fee = 10, Status = "排班" });
            dataList.Add(new MyDataItem() { ID = 16, DoctorName = "张某", Date = DateTime.Now, Time = "上午", Place = 3, Fee = 10, Status = "排班" });
            dataList.Add(new MyDataItem() { ID = 17, DoctorName = "李某", Date = DateTime.Now, Time = "下午", Place = 3, Fee = 10, Status = "排班" });
            dataList.Add(new MyDataItem() { ID = 18, DoctorName = "赵某", Date = DateTime.Now, Time = "中午", Place = 3, Fee = 10, Status = "排班" });
            dataList.Add(new MyDataItem() { ID = 19, DoctorName = "杨某", Date = DateTime.Now, Time = "上午", Place = 3, Fee = 10, Status = "停诊" });
            dataList.Add(new MyDataItem() { ID = 20, DoctorName = "黎某", Date = DateTime.Now, Time = "中午", Place = 3, Fee = 10, Status = "排班" });
            #endregion

            //添加下拉选项(序列)
            AddDropdownList1(sheet, rowCount);

            //添加下拉选项(指定数据)
            AddDropdownList2(workbook, sheet, rowCount);

            //插入数据
            for (int i = 0; i < dataList.Count; i++)
            {
                MyDataItem item = dataList[i];
                IRow dataRow = sheet.CreateRow(rowCount);

                dataRow.CreateCell(0).SetCellValue(string.Format("{0}({1})", item.DoctorName, item.ID));
                dataRow.CreateCell(1).SetCellValue(item.Date.ToString("yyyy/MM/dd"));
                dataRow.CreateCell(2).SetCellValue(item.Time);
                dataRow.CreateCell(3).SetCellValue(item.Place);
                dataRow.CreateCell(4).SetCellValue(item.Fee.ToString("N2"));
                dataRow.CreateCell(5);//.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, 0, 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(2);

                //一行最后一个方格的编号 即总的列数
                int cellCount = headerRow.LastCellNum;

                //有多少列
                int rowCount = sheet.LastRowNum;

                //读
                for (int i = 2; 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, 65535, 5, 5);
            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(0).CreateCell(0).SetCellValue("上午");
            sheet2.CreateRow(1).CreateCell(0).SetCellValue("中午");
            sheet2.CreateRow(2).CreateCell(0).SetCellValue("下午");
            sheet2.CreateRow(3).CreateCell(0).SetCellValue("晚上");

            IName range = workbook.CreateName();
            range.RefersToFormula = "a!$A$1:$A$4";
            range.NameName = "timeDic";

            CellRangeAddressList regions = new CellRangeAddressList(start, 65535, 2, 2);
            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; }
        }

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

时间: 2024-10-29 01:10:34

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

NPOI操作excel——利用反射机制,NPOI读取excel数据准确映射到数据库字段

> 其实需求很明确,就是一大堆不一样的excel,每张excel对应数据库的一张表,我们需要提供用户上传excel,我们解析数据入库的功能实现. 那么,这就涉及到一个问题:我们可以读出excel的表头,但是怎么知道每个表头具体对应数据库里面的字段呢? 博主经过一段时间的思考与构思,想到一法:现在的情况是我们有excel表A,对应数据库表B,但是A与B具体属性字段的映射关系我们不知.那我们是不是可以有一个A到B的映射文件C呢? 我想,说到这,大家就很明了了... 第一步:为每张excel创建一个与

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

//------------------------------------------------------------------------------------- // All Rights Reserved , Copyright (C) 2013 , DZD , Ltd . //------------------------------------------------------------------------------------- using System; us

使用NPOI读取Excel到DataTable

一.NPOI介绍: 使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写.NPOI是构建在POI 3.x版本之上的,它可以在没有安装Office的情况下对Word/Excel文档进行读写操作 二.安装NPOI 新建控制台应用程序>管理NuGet程序包>搜索NPOI>安装NPOI 三.下面是我需要的读取的Excel文件,数据格式如下: 四.添加ExcelHelper类: using System; using NPOI.SS.User

NPOI读取Excel,导入数据到Excel练习01

NPOI 2.2.0.0,初级读取导入Excel 1.读取Excel,将数据绑定到dgv上 1 private void button1_Click(object sender, EventArgs e) 2 { 3 List<Book> books = new List<Book>(); 4 //1.读取Excel文件 5 using (FileStream fsReder = File.OpenRead("练习.xlsx")) 6 { 7 //2.创建工作簿

NPOI操作Excel 002:读取Excel

本文讲述如何通过NPOI来读取Excel.需要准备的dll见:http://blog.csdn.net/yysyangyangyangshan/article/details/42614181环境.net2.0,Excel版本2003.NPOI读取Excel比较简单,只要抓住Excel的几个主要点即可.一般Excel通过这几部分构成的,book,sheet页,然后是sheet页里的行列.读取Excel则是先找到book,然后book内的sheet,之后就根据sheet里的第几行第几列进行读取内容

使用NPOI读取Excel数据到DataTable

现在XML文件的存储格式大行其道,但是也不是适用于所有情况,很多单位的数据交换还是使用Excel的形式.这就使得我们需要读取Excel内的数据,加载到程序中进行处理.但是怎样有效率的读取,怎样使程序保持健壮,这需要很大的努力. 我们如果要写一个动态链接库会很花费时间和精力,这就使得开源项目是个很有效率的选择. 在各类关于Excel的开源项目中NPOI是中国的程序员发起的,他的一大好处是直接处理Ole文件,用户不必安装Office.现在发展到2.0还可以自动判断Excel文件版本,我们自己判断文件

《.NET学习笔记》——使用NPOI读取Excel导入数据和导出Excel的功能

前提:由于有差不多两年时间没有进行B/S项目开发了,换了新工作,项目中要求有Excel导入数据库的功能,故保存下来供以后查看. 一.使用jQuery的uploadify插件完成选择文件并上传的功能: (1)先引入相关文件: <script src="../Scripts/uploadify/swfobject.js" type="text/javascript"></script> <link href="../Scripts

NPOI 导入Excel和读取Excel

1.整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet:行:Row:单元格Cell. 2.NPOI是POI的C#版本,NPOI的行和列的index都是从0开始 3.POI读取Excel有两种格式一个是HSSF,另一个是XSSF. HSSF和XSSF的区别如下: HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file format. XSSF is the

NPOI读取Excel到集合对象

之前做过的项目中有个需要读取Excel文件内容的需求,因此使用NPOI实现,写下以下代码,这个只是一个代码段,还有很多地方需要优化,希望能对大家有所帮助 public static IList<T> ReadListFromStream<T>(string fileName, Stream stream, bool ignoreFirstLine) where T : new() { string extendsion = Path.GetExtension(fileName).T