excel模板设置
私车公用单 | |||||||||
申请信息 | |||||||||
申请单号: | $header.ORDER_NO | 申请日期: | $header.CREATE_TIME | $auotheight | |||||
申请部门: | $header.APPLY_DEPT | 申请人: | $header.APPLY_USER | $auotheight | |||||
项目: | $header.PROJECT_RD_NAME | 客户: | $header.CUST_NAME | $auotheight | |||||
出差单号: | $header.BST_NO | $auotheight | |||||||
用车信息 | |||||||||
派车日期 | 使用人 | 车辆类型车牌 | 用车事由 | 出发地 | 目的地 | 行驶路线 | |||
$list.detail ASSIGN_DATE | $CAR_OWNER | $CAR_NUMBER | $REASON | $START_POINT | $END_POINT | $listend.ROUTE_NOTES | $auotheight | ||
签核信息 | |||||||||
序号 | 日期 | 步骤 | 签核部门 | 签核人 | 结果 | 签核意见 | |||
$list.ad SEQ | $EVENT_TIME | $AUDIT_DESC | $DEPT_NAME | $USER_NAME | $AUDIT_RESULT | $listend.AUDIT_MARK | $auotheight | ||
使用方式:
1.首先查询数据,DataSet ds=GetData(orderno);
2.然后调用,支持一个sheet模板导出多个数据sheet,多个sheet模板导出多个数据sheet
string fpath = "私车公用单.xls";
ExcelHelper.Helper excel = new ExcelHelper.Helper();
NPOI241.SS.UserModel.IWorkbook workbook = excel.Export(fpath, (book) =>
{
List sinfo = new List();
ExcelHelper.Helper.ExcelHelperSheetInfo info = new ExcelHelper.Helper.ExcelHelperSheetInfo();
sinfo.Add(info);
info.ModelSheet = book.GetSheetAt(0);
info.NewSheetData = new List
using Newtonsoft.Json;
using NPOI241.HSSF.Record;
using NPOI241.HSSF.UserModel;
using NPOI241.HSSF.Util;
using NPOI241.SS.UserModel;
using NPOI241.SS.UserModel.Charts;
using NPOI241.SS.Util;
using NPOI241.XSSF.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
namespace WebPortal.Common.ExcelHelper
{
public struct SimpleCell
{
///
/// 文本
///
public string T { get; set; }
///
/// colspan
///
public int C { get; set; }
///
/// rowspan
///
public int R { get; set; }
///
/// 样式 文本颜色,背景颜色,字体是否加粗,对齐,宽度
///
public string S { get; set; }
///
/// 备注
///
public string RK { get; set; }
}
public struct SimpleChart
{
///
/// 标题
///
public string Title { get; set; }
///
/// 类型 chart类型 bar和line
///
public string Type { get; set; }
///
/// 数据起始单元格
///
public int Col1 { get; set; }
///
/// 数据起始行
///
public int Row1 { get; set; }
///
/// 数据结束单元格
///
public int Col2 { get; set; }
///
/// 数据结束行
///
public int Row2 { get; set; }
///
/// 是否应用右边Y轴,默认左边Y轴
///
public bool RightY { get; set; }
}
public class SimpleTable
{
///
/// 行数据如
///
public List> Rows { get; set; }
///
/// 颜色
///
public List Colors { get; set; }
///
/// 样式
///
public List Styles { get; set; }
///
/// 冻结的行 只考虑冻结表头
///
public int FRow { get; set; }
///
/// 冻结的列
///
public int FCol { get; set; }
///
/// 图表信息
///
public List Chart { get; set; }
///
/// X轴数据起始单元格
///
public int Col1 { get; set; }
///
/// X轴数据起始行
///
public int Row1 { get; set; }
///
/// X轴数据结束单元格
///
public int Col2 { get; set; }
///
/// X轴数据结束行
///
public int Row2 { get; set; }
///
/// 是否设置右边Y轴
///
public bool RightY { get; set; }
///
/// 是否只读
///
public bool IsReadOnly { get; set; }
public string PWD { get; set; }
}
public struct CellStyleWrap
{
public int? Width { get; set; }
public ICellStyle CellStyle { get; set; }
public CellStyleWrap(int? w, ICellStyle cs)
: this()
{
this.Width = w;
this.CellStyle = cs;
}
}
public class Helper
{
void CreateChart(ISheet sheet, int col1, int col2, int row1, int row2, SimpleTable st)
{
IDrawing drawing = sheet.CreateDrawingPatriarch();
IClientAnchor anchor = drawing.CreateAnchor(0, 0, 0, 0, col1, row1, col2, row2);
var chart = drawing.CreateChart(anchor) as XSSFChart;
//生成图例
var legend = chart.GetOrCreateLegend();
//图例位置
legend.Position = LegendPosition.Top;
// X轴.
var bottomAxis = chart.ChartAxisFactory.CreateCategoryAxis(AxisPosition.Bottom);
//Y轴
IValueAxis leftAxis = chart.ChartAxisFactory.CreateValueAxis(AxisPosition.Left);
leftAxis.Crosses = (AxisCrosses.AutoZero);
//暂时不支持双y轴
IValueAxis rigthAxis = leftAxis;
//if (st.RightY)
//{
// rigthAxis = chart.ChartAxisFactory.CreateValueAxis(AxisPosition.Right);
// rigthAxis.Crosses = (AxisCrosses.AutoZero);
//}
//x轴
IChartDataSource xs = DataSources.FromNumericCellRange(sheet, new CellRangeAddress(st.Row1, st.Row2, st.Col1, st.Col2));
IBarChartData bardata = null;
ILineChartData linedata = null;
IScatterChartData scatterdata = null;
foreach (SimpleChart sc in st.Chart)
{
//图表
var data = DataSources.FromNumericCellRange(sheet, new CellRangeAddress(sc.Row1, sc.Row2, sc.Col1, sc.Col1));
SetDoubleData(sheet, sc.Col1, sc.Col2, sc.Row1, sc.Row2);
switch (sc.Type)
{
case "line":
if (linedata == null)
linedata = chart.ChartDataFactory.CreateLineChartData();
var sline = linedata.AddSeries(xs, data);
sline.SetTitle(sc.Title);
break;
case "bar":
if (bardata == null)
bardata = chart.ChartDataFactory.CreateBarChartData();
var sbar = bardata.AddSeries(xs, data);
sbar.SetTitle(sc.Title);
break;
case "scatter":
if (scatterdata == null)
scatterdata = chart.ChartDataFactory.CreateScatterChartData();
var stline = scatterdata.AddSeries(xs, data);
stline.SetTitle(sc.Title);
break;
default:
throw new Exception("暂不支持【" + sc.Type + "】类型的图表,只支持line、bar、scatter!");
}
}
if (bardata != null)
chart.Plot(bardata, bottomAxis, leftAxis);
if (linedata != null)
chart.Plot(linedata, bottomAxis, leftAxis);
if (scatterdata != null)
chart.Plot(scatterdata, bottomAxis, leftAxis);
}
public void SetDoubleData(ISheet sheet, int col1, int col2, int row1, int row2)
{
while (row1 <= row2)
{
IRow row = sheet.GetRow(row1);
if (row == null)
continue;
int begcol = col1;
while (begcol <= col2)
{
ICell cell = row.GetCell(begcol);
if (cell.CellType == CellType.String)
{
var value = cell.StringCellValue;
if (!string.IsNullOrWhiteSpace(value))
{
value = value.Replace(",", "").Trim();
double dbval;
if (double.TryParse(value, out dbval))
{
cell.SetCellType(CellType.Numeric);
cell.SetCellValue(dbval);
}
}
}
begcol += 1;
}
row1 += 1;
}
}
private void aa(List listcolor, short color)
{
if (color > PaletteRecord.STANDARD_PALETTE_SIZE)
return;
if (listcolor.IndexOf(color) < 0)
{
listcolor.Add(color);
}
}
private Dictionary CreateColor(HSSFWorkbook hssfWorkbook, List colors)
{
Dictionary dictret = new Dictionary();
HSSFPalette palette = hssfWorkbook.GetCustomPalette();
List listcolor = new List();
short index = 0;
IFont existsfont;
while (index < hssfWorkbook.NumberOfFonts)
{
existsfont = hssfWorkbook.GetFontAt(index);
aa(listcolor, existsfont.Color);
index += 1;
}
index = 0;
ICellStyle existscs;
while (index < hssfWorkbook.NumCellStyles)
{
existscs = hssfWorkbook.GetCellStyleAt(index);
aa(listcolor, existscs.FillBackgroundColor);
aa(listcolor, existscs.FillForegroundColor);
aa(listcolor, existscs.BottomBorderColor);
aa(listcolor, existscs.TopBorderColor);
aa(listcolor, existscs.LeftBorderColor);
aa(listcolor, existscs.RightBorderColor);
index += 1;
}
for (int i = 0; i < colors.Count; i++)
{
string color = colors[i];
string[] colorstr = color.Replace("rgba(", "").Replace("rgb(", "").Replace(")", "").Split(',');
byte r = Convert.ToByte(colorstr[0].Trim()), g = Convert.ToByte(colorstr[1].Trim()), b = Convert.ToByte(colorstr[2].Trim());
HSSFColor hc = palette.FindColor(r, g, b);
if (hc != null)
{
dictret.Add(color, hc.Indexed);
listcolor.Add(hc.Indexed);
continue;
}
short colorindex = PaletteRecord.FIRST_COLOR_INDEX;
short endcolorindex = PaletteRecord.STANDARD_PALETTE_SIZE;
while (colorindex < endcolorindex)
{
if (listcolor.IndexOf(colorindex) < 0)
{
palette.SetColorAtIndex(colorindex, r, g, b);
dictret.Add(color, colorindex);
listcolor.Add(colorindex);
break;
}
colorindex += 1;
}
}
return dictret;
}
private Dictionary CreateColor(XSSFWorkbook hssfWorkbook, List colors)
{
Dictionary dictret = new Dictionary();
List listcolor = new List();
for (int i = 0; i < colors.Count; i++)
{
string color = colors[i];
string[] colorstr = color.Replace("rgba(", "").Replace("rgb(", "").Replace(")", "").Split(',');
byte r = Convert.ToByte(colorstr[0].Trim()), g = Convert.ToByte(colorstr[1].Trim()), b = Convert.ToByte(colorstr[2].Trim());
dictret.Add(color, new XSSFColor(new byte[] { r, g, b }));
}
return dictret;
}
private Dictionary CreateCellStyle(IWorkbook book, ICellStyle df, List style, Dictionary diccolor)
{
Dictionary dicret = new Dictionary();
foreach (string str in style)
{
string[] strs = str.Split(';');
string fc = strs[0];
string bc = strs[1];
string fw = strs[2];
string al = strs[3];
string w = strs[4];
if (fw == "bold")
fw = "400";
ICellStyle cs;
if (fc != "" || bc != "" || fw != "" || al != "")
{
cs = book.CreateCellStyle();
cs.CloneStyleFrom(df);
}
else
{
cs = df;
}
short color;
if (bc != "" && diccolor.TryGetValue(bc, out color))
{
cs.FillForegroundColor = color;
cs.FillPattern = FillPattern.SolidForeground;
}
color = 0;
short fontcolor = 0;
if (fw != "")
short.TryParse(fw, out color);
if (fc != "")
diccolor.TryGetValue(fc, out fontcolor);
if (color > 0 || fontcolor > 0)
{
color *= 2;
IFont font = cs.GetFont(book);
IFont fontnew = book.CreateFont();
fontnew.Charset = font.Charset;
fontnew.Color = fontcolor == 0 ? font.Color : fontcolor;
fontnew.FontHeight = font.FontHeight;
fontnew.FontHeightInPoints = font.FontHeightInPoints;
fontnew.FontName = font.FontName;
fontnew.IsItalic = font.IsItalic;
fontnew.IsStrikeout = font.IsStrikeout;
fontnew.TypeOffset = font.TypeOffset;
fontnew.Underline = font.Underline;
fontnew.Boldweight = color == 0 ? font.Boldweight : color;
cs.SetFont(fontnew);
}
switch (al.ToLower())
{
case "center":
cs.Alignment = HorizontalAlignment.Center;
break;
case "right":
cs.Alignment = HorizontalAlignment.Right;
break;
}
int? with = null;
int widthtmp;
if (int.TryParse(w, out widthtmp))
with = widthtmp;
dicret.Add(str, new CellStyleWrap(with, cs));
}
return dicret;
}
private Dictionary CreateCellStyle(IWorkbook book, ICellStyle df, List style, Dictionary diccolor)
{
Dictionary dicret = new Dictionary();
foreach (string str in style)
{
string[] strs = str.Split(';');
string fc = strs[0];
string bc = strs[1];
string fw = strs[2];
string al = strs[3];
string w = strs[4];
if (fw == "bold")
fw = "400";
ICellStyle cs;
if (fc != "" || bc != "" || fw != "" || al != "")
{
cs = book.CreateCellStyle();
cs.CloneStyleFrom(df);
}
else
{
cs = df;
}
short color;
XSSFColor bcolor;
if (bc != "" && diccolor.TryGetValue(bc, out bcolor))
{
((XSSFCellStyle)cs).SetFillForegroundColor(bcolor);
cs.FillPattern = FillPattern.SolidForeground;
}
color = 0;
XSSFColor fontcolor = null;
bool hasfc = false;
if (fw != "")
short.TryParse(fw, out color);
if (fc != "")
hasfc = diccolor.TryGetValue(fc, out fontcolor);
if (color > 0 || hasfc)
{
color *= 2;
IFont font = cs.GetFont(book);
IFont fontnew = book.CreateFont();
fontnew.Charset = font.Charset;
if (!hasfc)
fontnew.Color = font.Color;
else
((XSSFFont)fontnew).SetColor(fontcolor);
fontnew.FontHeight = font.FontHeight;
fontnew.FontHeightInPoints = font.FontHeightInPoints;
fontnew.FontName = font.FontName;
fontnew.IsItalic = font.IsItalic;
fontnew.IsStrikeout = font.IsStrikeout;
fontnew.TypeOffset = font.TypeOffset;
fontnew.Underline = font.Underline;
fontnew.Boldweight = color == 0 ? font.Boldweight : color;
cs.SetFont(fontnew);
}
switch (al.ToLower())
{
case "center":
cs.Alignment = HorizontalAlignment.Center;
break;
case "right":
cs.Alignment = HorizontalAlignment.Right;
break;
}
int? with = null;
int widthtmp;
if (int.TryParse(w, out widthtmp))
with = widthtmp;
dicret.Add(str, new CellStyleWrap(with, cs));
}
return dicret;
}
public void ToExcel(string data, Stream stream, bool is2003)
{
try
{
SimpleTable st = JsonConvert.DeserializeObject(data);
IWorkbook book = null;
if (is2003)
{
book = new HSSFWorkbook();
}
else
{
book = new XSSFWorkbook();
}
ICellStyle dfcs = book.CreateCellStyle();
dfcs.Alignment = HorizontalAlignment.Left;
dfcs.VerticalAlignment = VerticalAlignment.Center;
dfcs.BorderBottom = BorderStyle.Thin;
dfcs.BorderLeft = BorderStyle.Thin;
dfcs.BorderRight = BorderStyle.Thin;
dfcs.BorderTop = BorderStyle.Thin;
if (st.IsReadOnly)
dfcs.IsLocked = true;
Dictionary dicstyle = null;
if (is2003)
{
Dictionary dicColor = CreateColor((HSSFWorkbook)book, st.Colors);
dicstyle = CreateCellStyle(book, dfcs, st.Styles, dicColor);
}
else
{
Dictionary dicColor = CreateColor((XSSFWorkbook)book, st.Colors);
dicstyle = CreateCellStyle(book, dfcs, st.Styles, dicColor);
}
ISheet sheet = book.CreateSheet();
IDrawing patr = sheet.CreateDrawingPatriarch();
int rowindex = 0;
foreach (List cells in st.Rows)
{
IRow row = sheet.CreateRow(rowindex);
int cellindex = 0;
foreach (SimpleCell sc in cells)
{
ICell cell = row.CreateCell(cellindex);
if (!string.IsNullOrEmpty(sc.T))
{
cell.SetCellValue(sc.T);
}
CellStyleWrap csw = default(CellStyleWrap);
if (sc.S != null && dicstyle.TryGetValue(sc.S, out csw))
{
cell.CellStyle = csw.CellStyle;
}
else
{
cell.CellStyle = dfcs;
}
if (!string.IsNullOrEmpty(sc.RK))
{
IComment comment = null;
if (is2003)
{
comment = patr.CreateCellComment(new HSSFClientAnchor(255, 125, 1023, 150, cellindex, rowindex, cellindex + 2, rowindex + 4));
comment.String = new HSSFRichTextString(sc.RK);
}
else
{
comment = patr.CreateCellComment(new XSSFClientAnchor(255, 125, 1023, 150, cellindex, rowindex, cellindex + 2, rowindex + 4));
comment.String = new XSSFRichTextString(sc.RK);
}
cell.CellComment = comment;
}
if (sc.C > 0 || sc.R > 0)
{
sheet.AddMergedRegion(new NPOI241.SS.Util.CellRangeAddress(rowindex, rowindex + (sc.R == 0 ? 0 : sc.R - 1), cellindex, cellindex + (sc.C == 0 ? 0 : sc.C - 1)));
}
cellindex += 1;
}
rowindex += 1;
}
int lastrowindex = rowindex;
List rows = st.Rows[st.FRow];
int index = 0;
foreach (SimpleCell sc in rows)
{
CellStyleWrap csw = default(CellStyleWrap);
if (sc.S != null && dicstyle.TryGetValue(sc.S, out csw) && csw.Width != null)
{
sheet.SetColumnWidth(index, csw.Width.Value * 256);
}
index += 1;
}
if (st.FCol > 0 || st.FRow > 0)
{
sheet.CreateFreezePane(st.FCol, st.FRow);
}
if (st.Chart != null && st.Chart.Count > 0)
{
CreateChart(sheet, 0, 0 + 10, lastrowindex + 3, lastrowindex + 3 + 20, st);
}
if (st.IsReadOnly)
{
sheet.ProtectSheet(st.PWD);
}
book.Write(stream);
}
catch
{
throw;
}
}
public void ToExcel(Stream stream, DataTable[] dts, NameValueCollection[] titles, bool is2003)
{
try
{
IWorkbook book = null;
if (is2003)
{
book = new HSSFWorkbook();
}
else
{
book = new XSSFWorkbook();
}
ICellStyle dfcs = book.CreateCellStyle();
dfcs.Alignment = HorizontalAlignment.Left;
dfcs.VerticalAlignment = VerticalAlignment.Center;
dfcs.BorderBottom = BorderStyle.Thin;
dfcs.BorderLeft = BorderStyle.Thin;
dfcs.BorderRight = BorderStyle.Thin;
dfcs.BorderTop = BorderStyle.Thin;
int i = 0;
foreach (DataTable dt in dts)
{
ISheet sheet = book.CreateSheet(dt.TableName);
NameValueCollection nvc = titles[i];
int rowindex = 0;
int cellindex = 0;
IRow row;
ICell cell;
row = sheet.CreateRow(rowindex);
foreach (string key in nvc)
{
cell = row.CreateCell(cellindex);
cell.CellStyle = dfcs;
cell.SetCellValue(nvc[key]);
cellindex += 1;
}
foreach (DataRow dr in dt.Rows)
{
rowindex += 1;
row = sheet.CreateRow(rowindex);
cellindex = 0;
foreach (string key in nvc)
{
cell = row.CreateCell(cellindex);
cell.CellStyle = dfcs;
cell.SetCellValue(dr[key].ToString());
cellindex += 1;
}
}
i += 1;
}
book.Write(stream);
}
catch
{
throw;
}
}
public class ExcelHelperSheetInfo
{
///
/// 新sheet数据,每一个数据项生产一个sheet页
///
public List