NPOI2.2.0.0实例详解(九)—设置EXCEL单元格【时间格式】

NPOI2.2.0.0实例详解(九)—设置EXCEL单元格【时间格式】

原文:http://blog.csdn.net/xxs77ch/article/details/50245391

复制代码

using System;  

using System.Collections.Generic;  

using System.Linq;  

using System.Text;  

using System.Threading.Tasks;  

using NPOI.HSSF.UserModel;  

using NPOI.SS.Formula.Eval;  

using NPOI.SS.Formula.Functions;  

using NPOI.SS.UserModel;  

using NPOI.XSSF.UserModel;  

using NPOI.POIFS.FileSystem;  

using NPOI.HPSF;  

using System.IO;  

using NPOI.SS.Util;  

using System.Drawing;  

using NPOI.HSSF.Util;  

namespace NPOI  

{  

class Program8  

    {  

static void Main(string[] args)  

        {  

//说明:设置时间格式  

//1.创建EXCEL中的Workbook           

            IWorkbook myworkbook = new XSSFWorkbook();  

//2.创建Workbook中的Sheet          

            ISheet mysheet = myworkbook.CreateSheet("sheet1");  

            mysheet.SetColumnWidth(0, 40 * 256);  

//3.创建Row中的Cell并赋值  

            IRow row0 = mysheet.CreateRow(0); row0.CreateCell(0).SetCellValue(DateTime.Now);  

            IRow row1 = mysheet.CreateRow(1); row1.CreateCell(0).SetCellValue(DateTime.Now);  

            IRow row2 = mysheet.CreateRow(2); row2.CreateCell(0).SetCellValue(DateTime.Now);  

            IRow row3 = mysheet.CreateRow(3); row3.CreateCell(0).SetCellValue(DateTime.Now);  

//4.创建CellStyle与DataFormat并加载格式样式  

            IDataFormat dataformat = myworkbook.CreateDataFormat();  

//【Tips】  

// 1.yyyy 年份;    yy 年份后两位  

// 2.MM 月份零起始;M 月份非零起始;  mmm[英文月份简写];mmmm[英文月份全称]  

// 3.dd   日零起始;d 日非零起始  

// 4.hh 小时零起始;h 小时非零起始[用于12小时制][12小时制必须在时间后面添加 AM/PM 或 上午/下午]  

// 5.HH 小时零起始;H 小时非零起始[用于24小时制]  

// 6.mm 分钟零起始;m 分钟非零起始  

// 7.ss 秒数零起始;s 秒数非零起始  

// 8.dddd 星期;ddd 星期缩写【英文】  

// 9.aaaa 星期;aaa 星期缩写【中文】  

            ICellStyle style0 = myworkbook.CreateCellStyle();  

            style0.DataFormat = dataformat.GetFormat("yyyy年MM月dd日 aaaa");  

            ICellStyle style1 = myworkbook.CreateCellStyle();  

            style1.DataFormat = dataformat.GetFormat("yyyy年MM月dd日 dddd");  

            ICellStyle style2 = myworkbook.CreateCellStyle();  

            style2.DataFormat = dataformat.GetFormat("h:mm:ss AM/PM");  

            ICellStyle style3 = myworkbook.CreateCellStyle();  

            style3.DataFormat = dataformat.GetFormat("h:mm:ss 上午/下午");  

//5.将CellStyle应用于具体单元格  

            row0.GetCell(0).CellStyle = style0;  

            row1.GetCell(0).CellStyle = style1;  

            row2.GetCell(0).CellStyle = style2;  

            row3.GetCell(0).CellStyle = style3;  

//6.保存         

            FileStream file = new FileStream(@"E:\myworkbook8.xlsx", FileMode.Create);  

            myworkbook.Write(file);  

            file.Close();  

        }  

    }  

}  
原文地址:https://www.cnblogs.com/grj001/p/12225399.html