NPOI 设置导出的excel内容样式
导出excel时,有时要根据需要加上一些样式,以上几种样式是我在项目中用到的
一、给单元格加背景色只需两步:一是创建单元格背景景色对象;二是给单元格绑定样式
//创建单元格背景颜色对象
HSSFPalette palette = wb.GetCustomPalette(); //调色板实例 palette.SetColorAtIndex(HSSFColor.Orange.Index, (byte), (byte), (byte));
HSSFColor hssFColor = palette.FindColor((byte), (byte), (byte)); ICellStyle cellStyleGround = wb.CreateCellStyle(); cellStyleGround.FillPattern = FillPattern.SolidForeground; //老版本可能这样写FillPatternType.SOLID_FOREGROUND;
cellStyleGround.SetFont(cs_content_Font);
cellStyleGround.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; //水平居中
cellStyleGround.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; //垂直居中
cellStyleGround.FillForegroundColor = hssFColor.Indexed;
//给单元格绑定样式
cell.CellStyle = cellStyleGround;
二、给单元格内的字加上样式
//创建工作簿
HSSFWorkbook wb = new HSSFWorkbook();
//创建工作表
HSSFSheet sheet = wb.createSheet();
//为工作表添加行
HSSFRow row = sheet.createRow();
//添加单元格
HSSFCell cell = row.createCell();
//创建字体
HSSFFont ftRed = wb.createFont();
ftRed.setStrikeout(true);
ftRed.setColor(HSSFColor.RED.index);
HSSFFont ftBlue = wb.createFont();
ftBlue.setColor(HSSFColor.BLUE.index);
//往单元格中写入的内容,并使用ft格式化"second"单词
String[] subStr = {
"first", "second"
};
String sText = subStr[] + "," + subStr[];
HSSFRichTextString textString = new HSSFRichTextString(sText);
textString.applyFont(
sText.indexOf(subStr[]),
sText.indexOf(subStr[]) + subStr[].length(),
ftRed
);
textString.applyFont(
sText.indexOf(subStr[]),
sText.indexOf(subStr[]) + subStr[].length(),
ftBlue
);
cell.setCellValue(textString);
三、附项目中用到的代码
private void ExportAllPlan(HttpContext context)
{
string title = DateTime.Now.AddYears().Year.ToString() + "年度领导人员因公出国(境)计划表";
HSSFWorkbook wb = new HSSFWorkbook();//创建工作薄
HSSFSheet sheet = (HSSFSheet)wb.CreateSheet(title); //创建工作表 //设置列头样式
HSSFCellStyle cs_Title = (HSSFCellStyle)wb.CreateCellStyle(); //创建列头样式
cs_Title.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; //水平居中
cs_Title.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; //垂直居中
HSSFFont cs_Title_Font = (HSSFFont)wb.CreateFont(); //创建字体
cs_Title_Font.FontHeightInPoints = ; //字体大小
cs_Title_Font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
cs_Title.SetFont(cs_Title_Font); //将字体绑定到样式
//设置列宽
for (int i = ; i < ; i++)
{
sheet.SetColumnWidth(i, * );
} //创建列头1行
HSSFRow row_Title_One = (HSSFRow)sheet.CreateRow();
string[] titleStr_One = { title, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" };
//设置列头样式
HSSFCellStyle cs_Title_one = (HSSFCellStyle)wb.CreateCellStyle(); //创建列头样式
cs_Title_one.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; //水平居中
cs_Title_one.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; //垂直居中
HSSFFont cs_Title_Font_one = (HSSFFont)wb.CreateFont(); //创建字体
cs_Title_Font_one.FontHeightInPoints = ; //字体大小
cs_Title_Font_one.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
cs_Title_one.SetFont(cs_Title_Font_one); //将字体绑定到样式 for (int i = ; i < titleStr_One.Length; i++)
{
HSSFCell cell_Title = (HSSFCell)row_Title_One.CreateCell(i); //创建单元格
row_Title_One.Height = *;
cell_Title.CellStyle = cs_Title_one; //将样式绑定到单元格
cell_Title.SetCellValue(titleStr_One[i]);
}
//合并
sheet.AddMergedRegion(new CellRangeAddress(, , , )); //创建列头2行
HSSFRow row_Title_Two = (HSSFRow)sheet.CreateRow();
string[] titleStr_Two = { "分类", "单位名称", "上年计划总数", "上年执行计划数", "上年计划外团组数", "今年申报总数", "压缩调整总数", "取消总数", "计划明细", "", "", "", "", "", "", "", "", "", "合作交流处意见", "俄罗斯处意见", "美洲亚太处意见", "西亚非洲处意见" }; //填充列头内容
for (int i = ; i < titleStr_Two.Length; i++)
{
HSSFCell cell_Title = (HSSFCell)row_Title_Two.CreateCell(i); //创建单元格
cell_Title.CellStyle = cs_Title; //将样式绑定到单元格
cell_Title.SetCellValue(titleStr_Two[i]);
}
//合并
sheet.AddMergedRegion(new CellRangeAddress(, , , ));
sheet.AddMergedRegion(new CellRangeAddress(, , , ));
sheet.AddMergedRegion(new CellRangeAddress(, , , ));
sheet.AddMergedRegion(new CellRangeAddress(, , , ));
sheet.AddMergedRegion(new CellRangeAddress(, , , ));
sheet.AddMergedRegion(new CellRangeAddress(, , , ));
sheet.AddMergedRegion(new CellRangeAddress(, , , ));
sheet.AddMergedRegion(new CellRangeAddress(, , , )); sheet.AddMergedRegion(new CellRangeAddress(, , , )); sheet.AddMergedRegion(new CellRangeAddress(, , , ));
sheet.AddMergedRegion(new CellRangeAddress(, , , ));
sheet.AddMergedRegion(new CellRangeAddress(, , , ));
sheet.AddMergedRegion(new CellRangeAddress(, , , ));
sheet.AddMergedRegion(new CellRangeAddress(, , , ));
//创建列头3行
HSSFRow row_Title_Three = (HSSFRow)sheet.CreateRow();
string[] titleStr_Three = { "", "", "", "", "", "", "", "", "序号", "姓名", "职务", "任务名称", "前往国家", "启程时间(月)", "任务类别", "必要性说明", "备注", "处理意见", "", "", "", "" }; //填充列头内容
for (int i = ; i < titleStr_Three.Length; i++)
{
HSSFCell cell_Title = (HSSFCell)row_Title_Three.CreateCell(i); //创建单元格
cell_Title.CellStyle = cs_Title; //将样式绑定到单元格
cell_Title.SetCellValue(titleStr_Three[i]);
} try
{
//设置单元格内容样式
HSSFCellStyle cs_content = (HSSFCellStyle)wb.CreateCellStyle(); //创建列头样式
cs_content.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; //水平居中
cs_content.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; //垂直居中
HSSFFont cs_content_Font = (HSSFFont)wb.CreateFont(); //创建字体
cs_content_Font.FontHeightInPoints = ; //字体大小
cs_content.SetFont(cs_content_Font); //将字体绑定到样式 //创建单元格背景颜色对象
HSSFPalette palette = wb.GetCustomPalette(); //调色板实例 palette.SetColorAtIndex(HSSFColor.Orange.Index, (byte), (byte), (byte));
HSSFColor hssFColor = palette.FindColor((byte), (byte), (byte)); ICellStyle cellStyleGround = wb.CreateCellStyle(); cellStyleGround.FillPattern = FillPattern.SolidForeground; //老版本可能这样写FillPatternType.SOLID_FOREGROUND;
cellStyleGround.SetFont(cs_content_Font);
cellStyleGround.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; //水平居中
cellStyleGround.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; //垂直居中
cellStyleGround.FillForegroundColor = hssFColor.Indexed; //获取计划数据
List<PlanToReport> plans = PlanToReportService.GetPlanByYear(DateTime.Now.AddYears().Year.ToString());
//出国处导出的大表中,只导出提交给出国处处长及以后流程的计划,提交给出国处处长之前的计划不导出
for (int i = ; i < plans.Count; i++)
{
StateMachineWorkflowInstance workflow = WorkflowRuntime.Current.GetRoot("PLANAPPLY", plans[i].ID);
string currState = workflow.CurrentState.Name;
string[] NoCanExportExcelPlan = ConfigurationManager.AppSettings["NoCanExportExcelPlanState"].Split(',');
for (int j = ; j < NoCanExportExcelPlan.Length; j++)
{
if (currState.Trim() == NoCanExportExcelPlan[j].Trim())
{
plans.RemoveAt(i);
continue;
}
} }
plans.Sort(new PlanToReportComparer());
int unitCategoryfistRow = ;
int planDiffRow = ;
int unitDiffRow = ;
int resultDifRow = ;
string tempCategory = string.Empty;
string tempUnitInfo = string.Empty;
string tempApprovalResult = string.Empty;
int colmNo = ;
for (int k = ; k < plans.Count; k++)
{
PlanToReport plan = plans[k];
UnitInfoBase unit = OilDigital.CGGL.BLL.UnitService.GetUnitByCode(plan.PlanUnitCode);
string[] planStr = { unit.Category.Name, unit.Name, plan.LastYearPlanSum.ToString(), plan.LastYearCarryOut.ToString(), plan.LastYearUnplanned.ToString(), PlanToReportService.GetPersonInPlan(plan.ID).Count.ToString(), plan.CompressTotal.ToString(), plan.CancelTotal.ToString() }; List<PlanPerson> persons = PlanToReportService.GetPersonInPlan(plan.ID);
persons.Sort(new PlanPersonComparer());
int indexNo = ; for (int i = ; i < persons.Count; i++)
{
PlanPersonApprovalService pps = new PlanPersonApprovalService();
// 取消审批
bool isDelete = pps.GetPlanPersonApprovalByIdAndType(persons[i].ID, "deletePerson") !=null;
//审批国家
PlanPersonApproval approvalCountry = pps.GetPlanPersonApprovalByIdAndType(persons[i].ID,"country");
bool hasAppCountry = approvalCountry != null;
//审批人员
PlanPersonApproval approvalPerson = pps.GetPlanPersonApprovalByIdAndType(persons[i].ID, "person");
bool hasAppPerson = approvalPerson != null; string[] personStr = { indexNo.ToString(), persons[i].Name, persons[i].Position, persons[i].JobName, persons[i].CountryName, persons[i].StartDate, persons[i].MissionType.ToString(), persons[i].Explain, persons[i].Remark, persons[i].ApprovalResults };
HSSFRow row = (HSSFRow)sheet.CreateRow(i + unitCategoryfistRow);
bool isMergedplan = false;
bool isMergedunit = false;
bool isMergedApprovalResult = false;
for (int j = ; j < ; j++)
{
HSSFCell cell = (HSSFCell)row.CreateCell(j);
cell.CellStyle = cs_content;
/*
* 导出数据时总体说明:
*填充数据8-16为人员数据,0-7和17-22为计划数据
*合并处理规则是:如果当前行和上一行不相同就合并上一行所有相同的,并对最后一行数据时行特殊处理。
*/
//1、填充计划数据
if (j >= && j <= )
{ //填充第一行时用计划数据 cell.SetCellValue(planStr[j]);
if (j == )
{
if (colmNo != && !tempCategory.Equals(planStr[j]))
{
sheet.AddMergedRegion(new CellRangeAddress(planDiffRow, colmNo - , j, j));
isMergedplan = true;
}
if (k == plans.Count - && i == persons.Count - )
{
sheet.AddMergedRegion(new CellRangeAddress(planDiffRow, colmNo, j, j));
isMergedplan = true;
}
}
if (j > )
{
if (colmNo != && !tempUnitInfo.Equals(planStr[]))
{
sheet.AddMergedRegion(new CellRangeAddress(unitDiffRow, colmNo - , j, j));
isMergedunit = true;
}
if (k == plans.Count - && i == persons.Count - )
{
sheet.AddMergedRegion(new CellRangeAddress(unitDiffRow, colmNo, j, j));
isMergedunit = true;
}
} }
//2、填充人员数据
else if (j >= && j <= )
{
if (j == )
{
cell.SetCellValue(new MissionTypeService().GetById(int.Parse(personStr[j - ])).Name);
}
else if (j == && hasAppCountry)
{
cell.SetCellValue(FmatterCellValue(persons[i], wb, "country"));
}
else if (j == && hasAppPerson)
{
cell.SetCellValue(FmatterCellValue(persons[i], wb, "person"));
}
else if (j == )
{
string cellval = persons[i].ApprovalResults;
if (!string.IsNullOrEmpty(persons[i].ApprovalResults))
{
cellval = persons[i].ApprovalResults.IndexOf("选0") > ? "合并" : persons[i].ApprovalResults;
} cell.SetCellValue(cellval);
// if (colmNo != 3 && !tempApprovalResult.Equals(new PlanProcess().GetFmatterApprovalResult(persons[i])) && !string.IsNullOrEmpty(new PlanProcess().GetFmatterApprovalResult(persons[i])))
if (colmNo != && !tempApprovalResult.Equals(new PlanProcess().GetFmatterApprovalResult(persons[i])))
{
sheet.AddMergedRegion(new CellRangeAddress(resultDifRow, colmNo - , j, j));
isMergedApprovalResult = true;
}
if (k == plans.Count - && i == persons.Count - )
{
sheet.AddMergedRegion(new CellRangeAddress(resultDifRow, colmNo, j, j));
isMergedApprovalResult = true;
}
if (!string.IsNullOrEmpty(persons[i].ApprovalResults))
{
cell.CellStyle = cellStyleGround;
}
// cell.SetCellValue(new PlanProcess().GetFmatterApprovalResult(persons[i]));
}
else
{
cell.SetCellValue(personStr[j - ]);
}
if (isDelete && j != )
{
cell.CellStyle = cellStyleGround;
} }
//3、填充意见数据
else
{
cell.SetCellValue("");
if (j > && tempUnitInfo.Equals(planStr[]))
{
sheet.AddMergedRegion(new CellRangeAddress(i + unitCategoryfistRow - , i + unitCategoryfistRow, j, j));
}
} }
if (isMergedplan) planDiffRow = colmNo;
if (isMergedunit) unitDiffRow = colmNo;
if (isMergedApprovalResult) resultDifRow = colmNo;
tempCategory = planStr[];
tempUnitInfo = planStr[];
tempApprovalResult = new PlanProcess().GetFmatterApprovalResult(persons[i]);
indexNo++;
colmNo++;
}
unitCategoryfistRow += persons.Count;
} }
catch (Exception ex)
{ throw new Exception("导出计划出错,原因:" + ex.Message);
} HttpResponse httpResponse = HttpContext.Current.Response;
httpResponse.Clear();
httpResponse.Buffer = true;
httpResponse.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(title + ".xls"));
httpResponse.ContentEncoding = Encoding.UTF8;
httpResponse.ContentType = "application/vnd.ms-excel; charset=UTF-8";
wb.Write(httpResponse.OutputStream);
httpResponse.End();
} //
private HSSFRichTextString FmatterCellValue(PlanPerson p, HSSFWorkbook wb, string FmatterType)
{
PlanPersonApproval approval = new PlanPersonApprovalService().GetPlanPersonApprovalByIdAndType(p.ID, FmatterType); StringBuilder countryName = new StringBuilder();
string[] selectCountry = approval.ApprovalResult.Split('、');
string[] allCountry = null;
if (FmatterType == "country")
{
allCountry = p.CountryName.Split('、');
}
if (FmatterType == "person")
{
allCountry = p.Name.Split('、');
} string needDeleteCountry = string.Empty;
for (int i = ; i < allCountry.Length; i++)
{
bool flag = true;
for (int j = ; j < selectCountry.Length; j++)
{
if (allCountry[i].Trim() == selectCountry[j].Trim())
{
flag = false;
}
}
if (flag)
{
if (string.IsNullOrEmpty(needDeleteCountry))
{
needDeleteCountry = allCountry[i];
}
else
{
needDeleteCountry += "、" + allCountry[i];
} }
}
String[] subStr = {
approval.ApprovalResult, needDeleteCountry
}; //创建字体
HSSFFont ftRed = (HSSFFont)wb.CreateFont();
ftRed.IsStrikeout=true;
ftRed.Color=HSSFColor.Red.Index;
ftRed.FontHeightInPoints = ;
String sText = subStr[] + "、" + subStr[];
HSSFRichTextString textString = new HSSFRichTextString(sText); textString.ApplyFont(
sText.IndexOf(subStr[]),
sText.IndexOf(subStr[]) + subStr[].Length,
ftRed
);
return textString;
}
NPOI 设置导出的excel内容样式的更多相关文章
- 设置导出的excel数据
/** * 设置导出的excel数据 * @param type $objPHPExcel * @param type $colModel * @param type $grid */public f ...
- c#使用NPOI快速导出到Excel
接上篇博文<C#快速导出到excel>:由于此种方法不能导出成.xlsx格式,为解决此问题,本次分享使用NPOI. 参考:https://www.cnblogs.com/lazyneal/ ...
- 表格导出到excel的样式消失该如何修改
工作中遇到一需求,要将后台的表格导出到excel后的表格样式该如何修改呢? 其实表格导出首先需要了解两个插件:jquery.table2excel.js和tableExport.js 1.第一步,写一 ...
- c#.net 使用NPOI导入导出标准Excel (asp.net winform csharp)
尝试过很多Excel导入导出方法,都不太理想,无意中逛到oschina时,发现了NPOI,无需Office COM组件且不依赖Office,顿时惊为天人,怀着无比激动的心情写下此文. 曾使用过的方法 ...
- ASP.NET- 使用NPOI导入导出标准Excel
尝试过很多Excel导入导出方法,都不太理想,无意中逛到oschina时,发现了NPOI,无需Office COM组件且不依赖Office,顿时惊为天人,怀着无比激动的心情写下此文. 曾使用过的方法 ...
- 使用NPOI导入导出标准Excel
尝试过很多Excel导入导出方法,都不太理想,无意中逛到oschina时,发现了NPOI,无需Office COM组件且不依赖Office,顿时惊为天人,怀着无比激动的心情写下此文. 曾使用过的方法 ...
- 使用NPOI快速导出导入Excel
这两天做项目需要导入导出EXCEL,是基于NPOI的封装,设计思路是使用DataTable,然后导出一个和DataTable一模一样的Excel表出来 github地址:https://github. ...
- 使用POI设置导出的EXCEL锁定指定的单元格
注:要锁定单元格需先为此表单设置保护密码,设置之后此表单默认为所有单元格锁定,可使用setLocked(false)为指定单元格设置不锁定. sheet.protectSheet("&quo ...
- 工作总结 npoi 模板 导出公式 excel
Apache POI(5):公式(formula) Apache POI(5):公式(formula) 2016年08月01日 17:44:49 阅读数:1145 package com.hthk ...
随机推荐
- 二十三、MongoDb 数据库介绍、安装、启动和连接(非关系型数据库)
1.数据库和文件的主要区别 1. 数据库有数据库表.行和列的概念,让我们存储操作数据更方便2. 数据库提供了非常方便的接口,可以让 nodejs.php java .net 很方便的实现增加修改删除功 ...
- 201621123023《Java程序设计》第6周学习总结
一.本周学习总结 1.1 面向对象学习暂告一段落,请使用思维导图,以封装.继承.多态为核心概念画一张思维导图或相关笔记,对面向对象思想进行一个总结. 二.书面作业 1. clone方法 1.1 在te ...
- “全栈2019”Java第五十六章:多态与字段详解
难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...
- [Maven实战-许晓斌]-[第二章]-2.7-2.8 Mave安装的最优建议和安装小结
2.7
- 【spring】SpringBoot之Servlet、Filter、Listener配置
转载自 http://blog.csdn.net/king_is_everyone/article/details/53116744 1.介绍 通过之前的文章来看,SpringBoot涵盖了很多配置, ...
- django2使用xadmin打造适合国人的后台管理系统(1)
python火了之后,学习python的人也越来越多了,python做web开发的话,flask.django是比较火的框架了,django是一个比较大的框架,也是一个快速开发利器.但是,django ...
- map集合根据value找key,默认取第一个key
private static String getKey(Map<String,String> map,String value){ String key=""; fo ...
- 经典排序的python实现
具体原理我这里就不解释了,可以查看数据结构课本或者百度百科 这里只给出相应的代码(很简洁) 1 __author__ = "WSX" class sort: def __init_ ...
- python 学习(pip工具的安装)
mac 电脑上使用终端命令 curl https://bootstrap.pypa.io/get-pip.py | python3 基于Python 3 pip --version pip3 list ...
- 最短路 CF954D Fight Against Traffic
CF954D Fight Against Traffic 题意描述: 给你一张无向图,一共有n个点(2 <= n <= 1000),由m条边连接起来(1 <= m <= 100 ...