导出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内容样式的更多相关文章

  1. 设置导出的excel数据

    /** * 设置导出的excel数据 * @param type $objPHPExcel * @param type $colModel * @param type $grid */public f ...

  2. c#使用NPOI快速导出到Excel

    接上篇博文<C#快速导出到excel>:由于此种方法不能导出成.xlsx格式,为解决此问题,本次分享使用NPOI. 参考:https://www.cnblogs.com/lazyneal/ ...

  3. 表格导出到excel的样式消失该如何修改

    工作中遇到一需求,要将后台的表格导出到excel后的表格样式该如何修改呢? 其实表格导出首先需要了解两个插件:jquery.table2excel.js和tableExport.js 1.第一步,写一 ...

  4. c#.net 使用NPOI导入导出标准Excel (asp.net winform csharp)

    尝试过很多Excel导入导出方法,都不太理想,无意中逛到oschina时,发现了NPOI,无需Office COM组件且不依赖Office,顿时惊为天人,怀着无比激动的心情写下此文. 曾使用过的方法 ...

  5. ASP.NET- 使用NPOI导入导出标准Excel

    尝试过很多Excel导入导出方法,都不太理想,无意中逛到oschina时,发现了NPOI,无需Office COM组件且不依赖Office,顿时惊为天人,怀着无比激动的心情写下此文. 曾使用过的方法 ...

  6. 使用NPOI导入导出标准Excel

    尝试过很多Excel导入导出方法,都不太理想,无意中逛到oschina时,发现了NPOI,无需Office COM组件且不依赖Office,顿时惊为天人,怀着无比激动的心情写下此文. 曾使用过的方法 ...

  7. 使用NPOI快速导出导入Excel

    这两天做项目需要导入导出EXCEL,是基于NPOI的封装,设计思路是使用DataTable,然后导出一个和DataTable一模一样的Excel表出来 github地址:https://github. ...

  8. 使用POI设置导出的EXCEL锁定指定的单元格

    注:要锁定单元格需先为此表单设置保护密码,设置之后此表单默认为所有单元格锁定,可使用setLocked(false)为指定单元格设置不锁定. sheet.protectSheet("&quo ...

  9. 工作总结 npoi 模板 导出公式 excel

    Apache POI(5):公式(formula) Apache POI(5):公式(formula) 2016年08月01日 17:44:49 阅读数:1145   package com.hthk ...

随机推荐

  1. C#多线程学习(五) 多线程的自动管理(定时器)

    Timer类:设置一个定时器,定时执行用户指定的函数.               定时器启动后,系统将自动建立一个新的线程,执行用户指定的函数. 初始化一个Timer对象:  Timer timer ...

  2. 菜鸟的Xamarin.Forms前行之路——绪言

    作者入门时间不是很久,差不多一年,期间自学的东西比较杂乱,到目前为止,编程方面的知识比较薄弱.之所以做这个系列,也只是因为做了两个月的Xamarin.Forms方面的东西,由于资料和自身实力的原因,过 ...

  3. [转]解读Unity中的CG编写Shader系列6——不透明度与混合

    1.不透明度当我们要将两个半透的纹理贴图到一个材质球上的时候就遇到混合的问题,由于前面的知识我们已经知道了片段着色器以及后面的环节的主要工作是输出颜色与深度到帧缓存中,所以两个纹理在每个像素上的颜色到 ...

  4. 安装npm及cnpm

    一.安装npm 1. 使用npm首先需要下载node.js 进入nodejs官网nodejs下载,如下图 : 选择适合自己的系统,我这里使用的是window10 64bit 2. 开始安装 **选好需 ...

  5. jquery鼠标经过水平180度翻转效果

    Html代码: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/htm ...

  6. 木马APP的简单分析(Android Killer分析)

    本文作者:三星s7edge 一.此贴目的:分析一个木马APP样本的行为.—————————————————————————————————————————————————-二.分析步骤及结果: 文件名 ...

  7. Ionic无法通过npm安装解决方案

    http://www.jianshu.com/p/5a99334eb62d 一般从 node.js官网下载安装完之后,npm也会同时安装完. 如果通过 $ npm install -g cordova ...

  8. POJ1330 Nearest Common Ancestors (JAVA)

    经典LCA操作.. 贴AC代码 import java.lang.reflect.Array; import java.util.*; public class POJ1330 { // 并查集部分 ...

  9. POJ2299 Ultra-QuickSort (JAVA)

    思路是分治,和归并排序一模一样,只是在归并的过程中,顺便统计后半部分序列比前半部分序列小的有多少个 但一直WA,最后是结果数量比较大,会超过int,用long就ac了..做题真坎坷 贴AC代码 imp ...

  10. 《软件工程综合实践专题》第三次作业——原型工具Axure RP8 的介绍

    一.为什么使用Axure Axure RP是一个专业的快速原型设计工具. Axure RP已被一些大公司采用.Axure RP的使用者主要包括商业分析师.信息架构师.可用性专家.产品经理.IT咨询师. ...