您的位置:首页 > Web前端 > CSS

封装对NPOIExcel的操作,方便的设置导出Excel的样式

2016-05-18 17:47 477 查看
下载:

http://pan.baidu.com/s/1boTpT5l

使用方法:

导入:
使用ReadToDataTable方法
导出:
      NPOIExcel.ExcelManagermanger1=newExcelManager(this.textBox2.Text,ExcelManager.DealType.exportExcel);
manger1.SetDataSource(dt,1);

//设置标题行
manger1.SetRangeStyle("A1","D1")
.SetCellMerge()
.SetFontColor(NPOIStyle.NPOIColor.Blue)
.SetBackgroundColor(NPOIStyle.NPOIColor.Yellow)
.SetFontBold()
.SetFontItalic()
.SetFontSize(18)
.SetCellText("2016这里是标题")
.SetEnd();
//设置数据
manger1.SetRangeStyle("a2","d5")
.SetFontName("微软雅黑")
.SetFontSize(12)
.SetHorizontalAlignment(NPOIStyle.Alignment.Left)
.SetBorderAll()
.SetEnd();
//设置尾行
manger1.SetRangeStyle("e8","f9")
.SetCellMerge()
.SetFontColor(NPOIStyle.NPOIColor.Red)
.SetFontItalic()
.SetFontSize(14)
.SetCellText("2016签名")
.SetBorderBottom()
.SetBorderRight()
.SetEnd();

//导出文件
manger1.ExportExcelFile();


源码:



usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Data;
usingNPOI.SS.UserModel;
usingSystem.IO;
usingNPOI.XSSF.UserModel;
usingNPOI.SS.Util;
usingNPOI.HSSF.Util;

namespaceNPOIExcel
{
publicclassPoint
{
publicintX{get;set;}
publicintY{get;set;}
}
publicclassRange
{
publicintFIRSTROW{get;set;}
publicintLASTROW{get;set;}
publicintFIRSTCOL{get;set;}
publicintLASTCOL{get;set;}
}

publicclassExcelManager
{
#region属性

privatestringinPutPath{get;set;}
privatestringoutPutPath{get;set;}
privateIWorkbookworkbook{get;set;}
privateISheetsheet{get;set;}

#endregion

#region初始化
//publicExcelManager(){}
///<summary>
///创建一个用于导入,导出数据的管理类
///</summary>
///<paramname="Path">文件路径</param>
///<paramname="type">设置路径为导入或导出</param>
publicExcelManager(stringPath,DealTypetype)
{
//设置导入文件的路径,workBook
if(type==DealType.importExcel)
{
inPutPath=Path;
using(FileStreamfile=newFileStream(inPutPath,FileMode.Open,FileAccess.Read))
{
workbook=WorkbookFactory.Create(file);
}
}
if(type==DealType.exportExcel)
{
outPutPath=Path;
workbook=newXSSFWorkbook();
sheet=workbook.CreateSheet("sheet1");
}

}

///<summary>
///对Excel的操作类型
///</summary>
publicenumDealType
{
importExcel,
exportExcel
}
#endregion

#region"基础样式设置---2016-05-17fengylcadd"
///<summary>
///设置范围内的样式
///</summary>
///<paramname="startPoint">开始的单元格:例-A1</param>
///<paramname="endPoint">结束的单元格:例-B1</param>
///<returns>样式</returns>
publicNPOIStyleSetRangeStyle(stringstartPoint,stringendPoint)
{
returnnewNPOIStyle(workbook,sheet,startPoint,endPoint);
}

#endregion

#region导入
///<summary>
///读取Excel到DataTable,默认第一行为列名
///</summary>
///<paramname="headRowCount">表头的行数,从表头下一行开始是数据</param>
///<returns>DataTable</returns>
publicDataTableReadExcelToDataTable(intheadRowCount=1)
{

using(FileStreamfile=newFileStream(inPutPath,FileMode.Open,FileAccess.Read))
{
workbook=WorkbookFactory.Create(file);
}

sheet=workbook.GetSheetAt(0);
DataTabledtl=newDataTable(sheet.SheetName.Trim());

IRowheadRow=sheet.GetRow(0);

intcolumnCount=headRow.Cells.Count;

for(intindex=0;index<=columnCount-1;index++)
{
if(headRow.Cells[index].Equals(null))
dtl.Columns.Add(string.Empty,typeof(string));
else
{
if(CellType.Numeric==headRow.Cells[index].CellType)
dtl.Columns.Add(headRow.Cells[index].NumericCellValue.ToString().Trim(),typeof(string));
else
dtl.Columns.Add(headRow.Cells[index].StringCellValue.Trim(),typeof(string));
}

}

for(intx=headRowCount;x<=sheet.LastRowNum;x++)
{
IRowcontentRow=sheet.GetRow(x);
if(contentRow.Equals(null))
continue;
else
{
DataRowdr=dtl.NewRow();
boolisEmpty=true;

for(inty=0;y<=columnCount-1;y++)
{
if(contentRow.GetCell(y).Equals(null))
{
dr[y]=string.Empty;
}
else
{
ICellcontentCell=contentRow.GetCell(y);
switch(contentCell.CellType)
{
caseCellType.Blank:
dr[y]=string.Empty;
break;
caseCellType.Boolean:
break;
caseCellType.Error:
break;
caseCellType.Formula:
dr[y]=contentCell.StringCellValue.Trim();
break;
caseCellType.Numeric:
{
if(DateUtil.IsCellDateFormatted(contentCell))
dr[y]=contentCell.DateCellValue.ToString("yyyy-MM-ddHH:mm:ss");
else
dr[y]=contentCell.NumericCellValue.ToString().Trim();
}
break;
caseCellType.String:
dr[y]=contentCell.StringCellValue.Trim();
break;
caseCellType.Unknown:
break;

}
isEmpty=string.IsNullOrEmpty(dr[y].ToString().Trim())&&isEmpty;
}
}

//非全空添加行
if(!isEmpty)dtl.Rows.Add(dr);
}
}
returndtl;
}
#endregion

#region导出
///<summary>
///设置数据源
///</summary>
///<paramname="dt">数据</param>
///<paramname="headEmptyLineCount">最上方留出的空行</param>
publicvoidSetDataSource(DataTabledt,intheadEmptyLineCount=0)
{

try
{
intTotalNum=dt.Rows.Count+headEmptyLineCount+1;//(加上空行)

//添加数据
addData(TotalNum,headEmptyLineCount+1,sheet,dt);
//标题设置
for(inti=0;i<dt.Columns.Count;i++)
{
sheet.GetRow(headEmptyLineCount).GetCell(i).SetCellValue(dt.Columns[i].ColumnName);
}

}
catch(Exceptionex)
{
throwex;
}

}
///<summary>
///导出文件
///</summary>
///<paramname="fileName">文件名,不指定为随机生成</param>
publicvoidExportExcelFile(stringfileName="")
{
Randomran=newRandom();
if(string.IsNullOrEmpty(fileName))
{
fileName="\\"+DateTime.Now.ToString("yyyyMMddHHmmssfff")+ran.Next(1000,9999).ToString()+".xlsx";
}
else
{
fileName="\\"+fileName+".xlsx";
}

stringCreatePath=outPutPath+fileName;
FileStreamNewFile=newFileStream(CreatePath,FileMode.Create);
workbook.Write(NewFile);
}
privatestaticvoidaddData(intTotalNum,intheadCount,ISheetsheet,DataTabledt)
{
//添加数据
for(inti=0;i<TotalNum;i++)
{
IRowrow=sheet.CreateRow(i);

for(intj=0;j<dt.Columns.Count;j++)
{
row.CreateCell(j);
if(i>=headCount)
{
try
{
doublecellData=double.Parse(dt.Rows[i-headCount][j].ToString());
row.CreateCell(j).SetCellValue(cellData);
}
catch
{
stringcellData=dt.Rows[i-headCount][j].ToString();
if(cellData.Trim().Length>1&&cellData.Substring(0,1)=="'")
{cellData=cellData.Substring(1,cellData.Length-1);}
row.CreateCell(j).SetCellValue(cellData);
}
}
}
}
}
#endregion
}
///<summary>
///设置样式
///</summary>
publicclassNPOIStyle
{
publicRangerange{get;set;}
publicISheetsheet{get;set;}
publicICellStylecellStyle{get;set;}
publicIFontcellFontStyle{get;set;}

publicNPOIStyle(IWorkbookworkbook,ISheetsheet,stringstartPoint,stringendPoint)
{
cellStyle=workbook.CreateCellStyle();
cellFontStyle=workbook.CreateFont();
this.sheet=sheet;
range=GetRange(startPoint,endPoint);

}

publicenumAlignment
{
Center,Fill,Left,Right,Bottom,Top
}
publicenumNPOIColor:short
{
Black=8,Brown=60,OliveGreen=59,DarkGreen=58,DarkTeal=56,
DarkBlue=18,Indigo=62,Grey80Percent=63,DarkRed=16,Orange=53,
DarkYellow=19,Green=17,Teal=21,Blue=12,BlueGrey=54,
Grey50Percent=23,Red=10,LightOrange=52,Lime=50,SeaGreen=57,
Aqua=49,LightBlue=48,Violet=20,Grey40Percent=55,Pink=14,
Gold=51,Yellow=13,BrightGreen=11,Turquoise=15,SkyBlue=40,
Plum=61,Grey25Percent=22,Rose=45,Tan=47,LightYellow=43,
LightGreen=42,LightTurquoise=41,PaleBlue=44,Lavender=46,
White=9,CornflowerBlue=24,LemonChiffon=26,Maroon=25,
Orchid=28,Coral=29,RoyalBlue=30,LightCornflowerBlue=31,Automatic=64
}
///<summary>
///把Excel列名字母转换为数字坐标
///</summary>
///<paramname="character">Excel列名</param>
///<returns>转换后的数字</returns>
publicstaticintAsc(stringcharacter)
{
character=character.ToUpper();
char[]arry=character.ToCharArray();
inttotal=0;
for(inti=0;i<character.Length;i++)
{
total+=(Convert.ToInt32(arry[i])-65)+26*i;
}
returntotal;
}
///<summary>
///把‘A1’类型转换成Point类型
///</summary>
///<paramname="point">字符点</param>
///<returns>Point</returns>
publicstaticPointGetPoint(stringpoint)
{
PointnewPoint=newPoint();
char[]arry=point.ToCharArray();

intindex=0;
for(inti=0;i<point.Length;i++)
{
if(Char.IsNumber(arry[i]))
{
index=i;
break;
}
}
newPoint.Y=Asc(point.Substring(0,index));
newPoint.X=int.Parse(point.Substring(index,point.Length-index))-1;
returnnewPoint;
}
///<summary>
///根据两个点确定一个范围
///</summary>
///<paramname="startPosition">Excel上的开始点</param>
///<paramname="endPosition">Excel上的结束点</param>
///<returns>范围</returns>
publicRangeGetRange(stringstartPosition,stringendPosition)
{
Rangerange=newRange();
Pointstart=GetPoint(startPosition);
Pointend=GetPoint(endPosition);

range.FIRSTROW=start.X;
range.LASTROW=end.X;
range.FIRSTCOL=start.Y;
range.LASTCOL=end.Y;

for(introw=range.FIRSTROW;row<=range.LASTROW;row++)
{
if(sheet.GetRow(row)==null)sheet.CreateRow(row);

for(intcol=range.FIRSTCOL;col<=range.LASTCOL;col++)
{
if(sheet.GetRow(row).GetCell(col)==null)sheet.GetRow(row).CreateCell(col);
}
}

returnrange;
}
///<summary>
///设置样式的必要设置:设置样式的范围
///</summary>
///<paramname="startPoint">范围起始点</param>
///<paramname="endPoint">范围结束点</param>
///<returns>设置样式的范围</returns>
publicNPOIStyleSetRange(stringstartPoint,stringendPoint)
{
this.range=GetRange(startPoint,endPoint);
returnthis;
}
///<summary>
///合并单元格
///</summary>
///<paramname="startPosition">合并开始的单元格</param>
///<paramname="endPosition">合并结束的单元格</param>
///<returns></returns>
publicNPOIStyleSetCellMerge()
{
//把excel单元格带字母坐标转换为数字坐标
CellRangeAddresscellRangeAddress=newCellRangeAddress(range.FIRSTROW,range.LASTROW,range.FIRSTCOL,range.LASTCOL);
this.sheet.AddMergedRegion(cellRangeAddress);
returnthis;
}
///<summary>
///设置字体大小
///</summary>
///<paramname="size">字体大小:9,10,11...</param>
///<returns>Manager</returns>
publicNPOIStyleSetFontSize(shortsize)
{
cellFontStyle.FontHeightInPoints=size;
returnthis;
}
///<summary>
///设置sheet页面上列的宽
///</summary>
///<paramname="size"></param>
///<returns></returns>
publicNPOIStyleSetSheetColumnWidthSize(shortsize)
{
sheet.DefaultColumnWidth=size;
returnthis;
}
///<summary>
///设置字体样式
///</summary>
///<paramname="FontName">字体:宋体,黑体...</param>
///<returns>Manager</returns>
publicNPOIStyleSetFontName(stringFontName)
{
cellFontStyle.FontName=FontName;
returnthis;
}
///<summary>
///设置字体加粗
///</summary>
///<returns>Manager</returns>
publicNPOIStyleSetFontBold()
{
cellFontStyle.Boldweight=(short)FontBoldWeight.Bold;
returnthis;
}
///<summary>
///设置字体下划线
///</summary>
///<returns>Manager</returns>
publicNPOIStyleSetFontUnderline()
{
cellFontStyle.Underline=FontUnderlineType.Single;
returnthis;
}
///<summary>
///设置字体下倾斜
///</summary>
///<returns>Manager</returns>
publicNPOIStyleSetFontItalic()
{
cellFontStyle.IsItalic=true;
returnthis;
}
///<summary>
///设置字体水平对齐
///</summary>
///<returns>Manager</returns>
publicNPOIStyleSetHorizontalAlignment(Alignmentalignment)
{
switch(alignment)
{
caseAlignment.Center:
cellStyle.Alignment=HorizontalAlignment.Center;
break;
caseAlignment.Fill:
cellStyle.Alignment=HorizontalAlignment.Fill;
break;
caseAlignment.Left:
cellStyle.Alignment=HorizontalAlignment.Left;
break;
caseAlignment.Right:
cellStyle.Alignment=HorizontalAlignment.Right;
break;
default:
break;
}
returnthis;
}
///<summary>
///设置字体垂直对齐
///</summary>
///<returns>Manager</returns>
publicNPOIStyleSetVerticalAlignment(Alignmentalignment)
{
switch(alignment)
{
caseAlignment.Center:
cellStyle.VerticalAlignment=VerticalAlignment.Center;
break;
caseAlignment.Fill:
cellStyle.VerticalAlignment=VerticalAlignment.Justify;
break;
caseAlignment.Top:
cellStyle.VerticalAlignment=VerticalAlignment.Top;
break;
caseAlignment.Bottom:
cellStyle.VerticalAlignment=VerticalAlignment.Bottom;
break;
default:
break;
}
returnthis;
}
///<summary>
///设置字体颜色
///</summary>
///<paramname="FontName">字体:宋体,黑体...</param>
///<returns>Manager</returns>
publicNPOIStyleSetFontColor(NPOIColorcolor)
{
cellFontStyle.Color=(short)color;
returnthis;
}
///<summary>
///设置单元格背景色
///</summary>
///<paramname="color"></param>
///<returns></returns>
publicNPOIStyleSetBackgroundColor(NPOIColorcolor)
{
cellStyle.FillPattern=FillPattern.SolidForeground;
cellStyle.FillForegroundColor=(short)color;
returnthis;
}
///<summary>
///设置单元格的文字
///</summary>
///<paramname="position"></param>
///<paramname="text"></param>
publicNPOIStyleSetCellText(stringtext)
{
sheet.GetRow(range.FIRSTROW).GetCell(range.FIRSTCOL).SetCellValue(text);
returnthis;
}
///<summary>
///设置边框(Range内每个单元格的四边)
///</summary>
///<returns></returns>
publicNPOIStyleSetBorderAll()
{
cellStyle.BorderBottom=BorderStyle.Thin;
cellStyle.BorderLeft=BorderStyle.Thin;
cellStyle.BorderRight=BorderStyle.Thin;
cellStyle.BorderTop=BorderStyle.Thin;
returnthis;
}
publicNPOIStyleSetBorderBottom()
{
cellStyle.BorderBottom=BorderStyle.Thin;
returnthis;
}
publicNPOIStyleSetBorderLeft()
{
cellStyle.BorderLeft=BorderStyle.Thin;
returnthis;
}
publicNPOIStyleSetBorderRight()
{
cellStyle.BorderRight=BorderStyle.Thin;
returnthis;
}
publicNPOIStyleSetBorderTop()
{
cellStyle.BorderTop=BorderStyle.Thin;
returnthis;
}

///<summary>
///样式设置结束,调用此方法生效
///</summary>
publicvoidSetEnd()
{
for(inti=range.FIRSTROW;i<=range.LASTROW;i++)
{
for(intj=range.FIRSTCOL;j<=range.LASTCOL;j++)
{
cellStyle.SetFont(cellFontStyle);
sheet.GetRow(i).GetCell(j).CellStyle=cellStyle;
}
}
}
}
}





                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: