在最近开发任务中使用到了第三方类库NPOI,简单总结一下自己使用的心得体会。如果存在漏洞或不足请多多指正。
代码如下(示例):
///
/// 导出Excel样例
///
///
public string GetExportExcelExamples()
{
string result = "导出失败";
try
{
int CurrRow = 0;//当前Excel写入的行数
#region 1、创建Excel格式,并写入数据
HSSFWorkbook workbook = new HSSFWorkbook();//初始化一个新的HSSFWorkbook实例
ISheet sheet = workbook.CreateSheet("销售财务统计表");//创建一个sheet表
//设置列宽
for (int i = 0; i < 13; i++)
{
sheet.SetColumnWidth(i, 20 * 130);
}
sheet.SetColumnWidth(0, 20 * 150);
//设置单元格样式类型(单元格样式【单元格图案、填充模式、单元格背景色、边框、是否自动换行】、字体样式【字体类型、字体大小、字体颜色、字体是否加粗】)
//(1)大标题格式
ICellStyleVo cellStyleVo = new ICellStyleVo(HSSFColor.Grey50Percent.Index, FillPattern.SolidForeground, HSSFColor.Grey50Percent.Index, BorderStyle.Thin, true);
FontStyleVo fontStyleVo = new FontStyleVo("华文行楷", 18 * 18, HSSFColor.White.Index, false);
ICellStyle bigHeadStyle = SetICellStyle(workbook, cellStyleVo, fontStyleVo);
//(2)表格标题格式
cellStyleVo = new ICellStyleVo(HSSFColor.Grey50Percent.Index, FillPattern.SolidForeground, HSSFColor.Grey50Percent.Index, BorderStyle.Thin, true);
fontStyleVo = new FontStyleVo("华文行楷", 15 * 15, HSSFColor.White.Index, false);
ICellStyle tableHeadStyle = SetICellStyle(workbook, cellStyleVo, fontStyleVo);
//(3)表格正文格式(加粗)
cellStyleVo = new ICellStyleVo(HSSFColor.Grey40Percent.Index, FillPattern.SolidForeground, HSSFColor.Grey40Percent.Index, BorderStyle.Thin, true);
fontStyleVo = new FontStyleVo("华文行楷", 15 * 15, HSSFColor.Black.Index, true);
ICellStyle tableTextBoldStyle = SetICellStyle(workbook, cellStyleVo, fontStyleVo);
//(4)表格正文格式(不加粗)
cellStyleVo = new ICellStyleVo(HSSFColor.Grey25Percent.Index, FillPattern.SolidForeground, HSSFColor.Grey25Percent.Index, BorderStyle.Thin, true);
fontStyleVo = new FontStyleVo("华文行楷", 15 * 15, HSSFColor.Black.Index, false);
ICellStyle tableTextStyle = SetICellStyle(workbook, cellStyleVo, fontStyleVo);
#region 1.1、写入头部信息
sheet.AddMergedRegion(new CellRangeAddress(CurrRow, CurrRow, 0, 12));//合并单元格
IRow rowH = sheet.CreateRow(CurrRow);//创建一行
ICell cell = rowH.CreateCell(0);//创建一列
cell.SetCellValue("年终销售业绩财务数据统计表—动态分析");
cell.CellStyle = bigHeadStyle;//设置单元格样式
CurrRow += 2;
#endregion
#region 1.2、写入表格信息
//表格头部
rowH = sheet.CreateRow(CurrRow);
for (int i = 0; i < 13; i++)
{
cell = rowH.CreateCell(i);
if (i > 0)
cell.SetCellValue(i + "月");
cell.CellStyle = tableHeadStyle;
}
CurrRow += 1;
//表格Body
int[,] saleData = new int[,]
{
{ 5,28,50,69,58,122,134,158,28,93,94,183},
{ 150,125,24,82,58,114,81,85,124,25,94,72},
{ 138,123,68,85,5,12,34,58,128,83,114,83},
{ 18,4,50,69,58,22,34,118,128,43,88,133},
{ 8,65,150,169,158,22,34,134,128,113,35,138},
{ 132,128,30,79,88,122,184,58,128,56,63,156},
{ 10,28,150,169,58,142,43,78,28,73,124,153}
};//销售数据
for (int i = 0; i < saleData.GetLength(0); i++)//数组行数
{
rowH = sheet.CreateRow(CurrRow);
cell = rowH.CreateCell(0);
cell.SetCellValue("销售"+ (i + 1) +"部");
cell.CellStyle = tableTextStyle;
for (int j = 0; j < saleData.GetLength(1); j++)//数组列数
{
cell = rowH.CreateCell(j + 1);
cell.SetCellValue(saleData[i, j]);
cell.CellStyle = tableTextStyle;
}
CurrRow += 1;
}
#endregion
#region 1.3、插入图片
//下拉菜单
rowH = sheet.CreateRow(CurrRow);
cell = rowH.CreateCell(11);
cell.SetCellValue("下拉框");
cell.CellStyle = tableHeadStyle;
cell = rowH.CreateCell(12);
cell.SetCellValue("请选择");
cell.CellStyle = tableHeadStyle;
CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(CurrRow, CurrRow, 12, 12);
DVConstraint dVConstraint = DVConstraint.CreateExplicitListConstraint(new string[] { "销售1部", "销售2部", "销售3部", "销售4部", "销售5部", "销售6部", "销售7部" });
HSSFDataValidation dataValidate = new HSSFDataValidation(cellRangeAddressList, dVConstraint);
sheet.AddValidationData(dataValidate);
CurrRow += 1;
//簇状柱状图
string picPath = "C:/Users/Administrator/Desktop/Export/柱状图.png";
byte[] bytes = System.IO.File.ReadAllBytes(picPath);
int pictureIdx = workbook.AddPicture(bytes, PictureType.PNG);
HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();//在sheet中创建画布
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, 0, 11, 13, 38);//设置锚点(在起始单元格的X坐标0-1023,Y的坐标0-255,在终止单元格的X坐标0-1023,Y的坐标0-255,起始单元格列数,行数,终止单元格列数,行数)
HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);//把图片插到相应的位置
pict.Resize();//自动调节图片大小,防止图片被拉伸变形
#endregion
#endregion
#region 2、文件导出
string path = "C:/Users/Administrator/Desktop/Export/Example1.xls";
if (System.IO.File.Exists(path))
{
File.Delete(Path.GetFullPath(path));
}
FileStream file = new FileStream(path, FileMode.Create);
workbook.Write(file);
file.Close();
#endregion
result = "导出成功";
}
catch (Exception ex)
{
object msg = string.Concat("ExportExcels(GetExportExcelExamples)——导出Excel样例");
Log4NetHelper.ErrorLog(msg, ex);
}
return result;
}
///
/// 设置单元格样式
///
/// Excel工作单元
/// 单元格图案
/// 填充模式
/// 单元格背景色
/// 边框
/// 是否自动换行
/// 字体类型
/// 字体大小
/// 字体颜色
/// 字体是否加粗
///
public ICellStyle SetICellStyle(HSSFWorkbook workbook, ICellStyleVo cellStyleVo, FontStyleVo fontStyleVo)
{
ICellStyle cellStyle = workbook.CreateCellStyle();
#region [+]设置通用样式
#region [+]1、单元格通用样式
cellStyle.VerticalAlignment = VerticalAlignment.Center;//垂直居中
cellStyle.Alignment = HorizontalAlignment.Center;//水平居中
//设置单元格的背景和图案(注意坑:顺序)
cellStyle.FillBackgroundColor = cellStyleVo.FillBackgroundColor;//背景
cellStyle.FillPattern = cellStyleVo.FillPattern;//填充模式(必须设置)
cellStyle.FillForegroundColor = cellStyleVo.FillForegroundColor;//图案
//设置边框
//cellStyle.BorderTop = cellStyleVo.BorderStyle;
//cellStyle.BorderBottom = cellStyleVo.BorderStyle;
//cellStyle.BorderLeft = cellStyleVo.BorderStyle;
//cellStyle.BorderRight = cellStyleVo.BorderStyle;
//自动换行
cellStyle.WrapText = cellStyleVo.IsWrapText;
#endregion
#region [+]2、字体通用样式
IFont font = workbook.CreateFont();
font.FontName = fontStyleVo.FontName;//字体类型
font.FontHeight = fontStyleVo.FontHeight;//字体大小
font.Color = fontStyleVo.fontColor;//字体颜色
font.IsBold = fontStyleVo.IsBold;//字体是否加粗
cellStyle.SetFont(font);//把字体应用到当前样式
#endregion
return cellStyle;
#endregion
}
///
/// 单元格样式模型
///
public class ICellStyleVo
{
///
/// 单元格图案
///
public short FillForegroundColor { get; set; } = HSSFColor.White.Index;
///
/// 填充模式
///
public FillPattern FillPattern { get; set; } = FillPattern.SolidForeground;
///
/// 单元格背景色
///
public short FillBackgroundColor { get; set; } = HSSFColor.White.Index;
///
/// 边框
///
public BorderStyle BorderStyle { get; set; } = BorderStyle.None;
///
/// 是否自动换行
///
public bool IsWrapText { get; set; } = false;
public ICellStyleVo(short FillForegroundColor = HSSFColor.White.Index, FillPattern FillPattern = FillPattern.SolidForeground, short FillBackgroundColor = HSSFColor.White.Index, BorderStyle BorderStyle = BorderStyle.Thin, bool IsWrapText = false)
{
this.FillForegroundColor = FillForegroundColor;
this.FillPattern = FillPattern;
this.FillBackgroundColor = FillBackgroundColor;
this.BorderStyle = BorderStyle;
this.IsWrapText = IsWrapText;
}
}
///
/// 字体样式模型
///
public class FontStyleVo
{
///
/// 字体类型
///
public string FontName { get; set; } = "宋体";
///
/// 字体大小
///
public double FontHeight { get; set; } = 15 * 15;
///
/// 字体颜色
///
public short fontColor { get; set; } = HSSFColor.Black.Index;
///
/// 字体是否加粗
///
public bool IsBold { get; set; } = false;
public FontStyleVo(string FontName = "宋体", double FontHeight = 15 * 15, short fontColor = HSSFColor.Black.Index, bool IsBold = false)
{
this.FontName = FontName;
this.FontHeight = FontHeight;
this.fontColor = fontColor;
this.IsBold = IsBold;
}
}
例如:合并第一列中的第1~3行
//正确使用方法
int CurrRow = 0;
IRow rowTemp = sheet.CreateRow(CurrRow);
sheet.AddMergedRegion(new CellRangeAddress(CurrRow, CurrRow + 3, 0, 0));
cell = rowTemp.CreateCell(0);
cell.SetCellValue("学习");
//错误使用方法
int CurrRow = 3;
IRow rowTemp = sheet.CreateRow(CurrRow);
sheet.AddMergedRegion(new CellRangeAddress(CurrRow - 3, CurrRow, 0, 0));
cell = rowTemp.CreateCell(0);
cell.SetCellValue("学习");
目前NPOI对基础的表格导出的API比较完善,但对于高级Chart图的开发接口比较匮乏。