备料(添加引用):
using System.IO;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
1—自定义辅助类excelExportModel
private string _errContent;
private IWorkbook _workBook;
public string getErrDescription
{
get{return _errContent;}
}
/// <summary>
/// 导出excel
/// </summary>
/// <param name="view"></param>
/// <param name="fileType"></param>
public bool ExcelOut(IDynamicFormView view ,string fileType="xlsx")
{
bool result = false;
//--2-- Checkup
if(string.Compare(fileType,"xls",true)==0){
_workBook = new HSSFWorkbook();
}
else if (string.Compare(fileType, "xlsx", true) == 0)
{
_workBook = new XSSFWorkbook();
}
else {
_errContent = "建立Excel表格失败";
return result;
}
//--3--2 initialize excel style
result = initExcelStyle(view,_workBook,fileType);
//--8-- return values
return result;
}
主业务函数
/// <summary>
/// 初始化表格样式
/// </summary>
/// <param name="wbook"></param>
/// <returns></returns>
private bool initExcelStyle(IDynamicFormView view,IWorkbook wbook,string fileType)
{
int i = 0;
bool result = false;
List<Field> outFieldKeys = new List<Field>();
#region [ 3-1 Business]
ICellStyle style = wbook.CreateCellStyle();
style.Alignment = HorizontalAlignment.Center; //左右居中
style.VerticalAlignment = VerticalAlignment.Center; //上下居中
style.WrapText = true; //自动换 行
style.BorderTop = BorderStyle.Thin;
style.BorderLeft = BorderStyle.Thin;
style.BorderRight = BorderStyle.Thin;
style.BorderBottom = BorderStyle.Thin;
//字体
IFont headFont = wbook.CreateFont();
headFont.IsBold = true;
headFont.FontName = "宋体";
headFont.FontHeightInPoints = (short)12; //字体大小
//另一个样式
ICellStyle headStyle = wbook.CreateCellStyle();
headStyle.CloneStyleFrom(style);
headStyle.SetFont(headFont);
headStyle.IsLocked = true;
//另一个字体样式
IFont columnHeadFont = wbook.CreateFont();
columnHeadFont.FontName = "宋体";
columnHeadFont.FontHeightInPoints = (short)10;
//列头的样式
ICellStyle columnStyle = wbook.CreateCellStyle();
columnStyle.CloneStyleFrom(style);
columnStyle.SetFont(columnHeadFont);
#endregion
#region [ 3-2 init Entity]
var entity = view.BusinessInfo.GetEntity("F_PAEZ_EntityCal");
foreach (Field fId in entity.Fields)
{
FieldAppearance fieldAp = view.LayoutInfo.GetFieldAppearance(fId.Key);
if (view.StyleManager.GetVisible(fieldAp) && fId.IsExportFieldTemplateControl() && fieldAp.IsVisible(view.OpenParameter.Status))
{
outFieldKeys.Add(fId); //构建需要导出的字段
}
}
DynamicObjectCollection curRows = null;
if (view.Model.GetEntityDataObject(entity) == null)
{
curRows = new DynamicObjectCollection(view.Model.DataObject.DynamicObjectType);
curRows.Add(view.Model.DataObject);
}
else
{
curRows = view.Model.GetEntityDataObject(entity);
}
#endregion
#region [ 3-3 pull data into the excel]
ISheet sheet = wbook.CreateSheet(view.BusinessInfo.GetElement("F_PAEZ_EntityCal").Name);
IRow rowHeader = sheet.CreateRow(0); //创建表头行
for (i = 0; i < outFieldKeys.Count(); i++)
{
ICell cell = rowHeader.CreateCell(i);
cell.SetCellValue(outFieldKeys[i].Name.ToString());
cell.CellStyle = headStyle;
sheet.SetColumnWidth(i, 256 * 15);
}
int rowLine = 0;
if(!curRows.IsNullOrEmpty()){
foreach(var item in curRows){
rowLine++;
IRow row = sheet.CreateRow(rowLine);
int j = 0;
foreach(var field in outFieldKeys){
ICell cell = row.CreateCell(j);
columnStyle.WrapText = true;
cell.CellStyle = columnStyle;
//--3--5 set value
if(field is DateTimeField || field is TimeField){
string values = item[field.Key] == null ? "" : item[field.Key].ToString();
DateTime dt = Convert.ToDateTime(values);
string formatStr = view.LayoutInfo.GetFieldAppearance(field.Key).DisplayFormatString;
cell.SetCellValue(dt.ToString(formatStr));
}
else if (field is DecimalField)
{
double nc = Convert.ToDouble(item[field.Key] == null ? "" : item[field.Key].ToString());
if (!nc.Equals(0))
{
cell.SetCellValue(nc);
}
}
else {
string values = item[field.Key] == null ? "" : item[field.Key].ToString();
if (!string.IsNullOrEmpty(values.Trim())) cell.SetCellValue(values);
}
j++;
}
} //foreach_END
}
#endregion
string fileName=string.Format("{0}_{1}",view.BusinessInfo.GetForm().Name,
DateTime.Now.ToString("yyyyMMddHHmmssff") );
string[] illegalStrs = new string[] { "/", "\\" };
foreach(var str in illegalStrs){
fileName = fileName.Replace(str, "");
}
string filePath = PathUtils.GetPhysicalPath(KeyConst.TEMPFILEPATH, fileName);
string outServicePath = PathUtils.GetServerPath(KeyConst.TEMPFILEPATH, fileName);
filePath += "."+fileType;
outServicePath += "." + fileType; //浏览器访问地址
using(Stream stream=File.OpenWrite(filePath)){
wbook.Write(stream);
}
//声明下载界面,下载excel
DynamicFormShowParameter param = new DynamicFormShowParameter();
param.FormId = "BOS_FileDownLoad";
param.OpenStyle.ShowType=ShowType.Modal;
param.CustomParams.Add("IsExportData","true");
param.CustomParams.Add("url", outServicePath);
view.ShowForm(param);
result = true;
//--8-- return values
return result;
}