在操作Excel时候一些特殊值的转换是在所难免的,下面就给出转换方法大同小异,代码如下:
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();ISheet sheet = hssfWorkbook.CreateSheet("Sheet1");//设置第一列(Cell) 宽度sheet.SetColumnWidth(0, 5000);//创建格式化 实例对象IDataFormat format = hssfWorkbook.CreateDataFormat();// 保留两位小数格式// 创建一个单元格 "1.20"ICell cell = sheet.CreateRow(0).CreateCell(0);//设置单元格的值cell.SetCellValue(1.2);ICellStyle cellStyle = hssfWorkbook.CreateCellStyle();//格式化值cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00");cell.CellStyle = cellStyle;//货币 "¥20,000"ICell cell2 = sheet.CreateRow(1).CreateCell(0);cell2.SetCellValue(20000);ICellStyle cellStyle2 = hssfWorkbook.CreateCellStyle();cellStyle2.DataFormat = format.GetFormat("¥#,##0");cell2.CellStyle = cellStyle2;//科学计数法 "3.15E+00"ICell cell3 = sheet.CreateRow(2).CreateCell(0);cell3.SetCellValue(3.151234);ICellStyle cellStyle3 = hssfWorkbook.CreateCellStyle();cellStyle3.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00E+00");cell3.CellStyle = cellStyle3;//百分比 "99.33%"ICell cell4 = sheet.CreateRow(3).CreateCell(0);cell4.SetCellValue(0.99333);ICellStyle cellStyle4 = hssfWorkbook.CreateCellStyle();cellStyle4.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00%");cell4.CellStyle = cellStyle4;//电话号码 "021-65881234"ICell cell5 = sheet.CreateRow(4).CreateCell(0);cell5.SetCellValue(02165881234);ICellStyle cellStyle5 = hssfWorkbook.CreateCellStyle();cellStyle5.DataFormat = format.GetFormat("000-00000000");cell5.CellStyle = cellStyle5;//金额大写 - 壹贰叁 元ICell cell6 = sheet.CreateRow(5).CreateCell(0);cell6.SetCellValue(123);ICellStyle cellStyle6 = hssfWorkbook.CreateCellStyle();cellStyle6.DataFormat = format.GetFormat("[DbNum2][$-804]0 元");cell6.CellStyle = cellStyle6;//日期格式化ICell cell7 = sheet.CreateRow(6).CreateCell(0);cell7.SetCellValue(new DateTime(2004, 5, 6));ICellStyle cellStyle7 = hssfWorkbook.CreateCellStyle();cellStyle7.DataFormat = format.GetFormat("yyyy年m月d日");cell7.CellStyle = cellStyle7;//日期格式化ICell cell8 = sheet.CreateRow(7).CreateCell(0);cell8.SetCellValue(new DateTime(2005, 11, 6));ICellStyle cellStyle8 = hssfWorkbook.CreateCellStyle();cellStyle8.DataFormat = format.GetFormat("yyyy年m月d日");cell8.CellStyle = cellStyle8;FileStream file = new FileStream(@"test.xls", FileMode.Create);hssfWorkbook.Write(file);file.Close();
在上面的代码中转换的地方有两个方法:
1.HSSFDataFormat.GetBuiltinFormat()这种标识转换的格式是Excel内嵌的格式,如:“0.00”,完整的Excel内嵌格式列表大家可以看下图。2.format.GetFormat("000-00000000")这种则是根据格式去格式化
Excel内嵌格式,如图:
新闻热点
疑难解答