帮助类

using OfficeOpenXml;
using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web; namespace EpPlus.Demo.Models
{
public class EpPlusHelper
{
ExcelPackage package;
ExcelWorksheet worksheet; /// <summary>
/// 构造函数
/// </summary>
/// <param name="sheetName"></param>
/// <param name="path"></param>
public EpPlusHelper(string sheetName = "", string path = "")
{
try
{
if (!string.IsNullOrEmpty(path))
{
package = new ExcelPackage(new FileInfo(path));
}
else
{
package = new ExcelPackage();
} if (package.Workbook.Worksheets.Count > 0)
{
worksheet = package.Workbook.Worksheets[0];
}
else
{
CreateSheet(DateTime.Now.ToString("yyyyMMdd"));
} if (!string.IsNullOrWhiteSpace(sheetName))
{
worksheet.Name = sheetName;
}
}
catch (Exception ex)
{
throw ex;
}
} /// <summary>
/// 创建工作薄
/// </summary>
/// <param name="sheetName"></param>
public void CreateSheet(string sheetName)
{
try
{
worksheet = package.Workbook.Worksheets.Add(sheetName);//创建worksheet
}
catch (Exception ex)
{
throw ex;
}
} /// <summary>
/// 切换工作薄
/// </summary>
/// <param name="index"></param>
public void ChangeSheet(int index)
{
try
{
worksheet = package.Workbook.Worksheets[index];
}
catch (Exception ex)
{
throw ex;
}
} /// <summary>
/// 切换工作簿
/// </summary>
/// <param name="sheetName"></param>
public void ChangeSheet(string sheetName)
{
try
{
worksheet = package.Workbook.Worksheets[sheetName];
}
catch (Exception ex)
{
throw ex; }
} /// <summary>
/// 保存excel
/// </summary>
/// <param name="password"></param>
public void SaveExcel(HttpResponseBase response, string excelName)
{
try
{
if (package != null)
{
if (!string.IsNullOrEmpty(excelName))
{
//package.Save();
//package.SaveAs();
response.BinaryWrite(package.GetAsByteArray());
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.AddHeader("content-disposition", "attachment; filename=" + excelName + ".xlsx");
}
else
{
response.BinaryWrite(package.GetAsByteArray());
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.AddHeader("content-disposition", "attachment; filename=" + (DateTime.Now.ToString("yyyyMMddHHmmss")) + ".xlsx");
}
}
}
catch (Exception ex)
{
throw ex;
}
} /// <summary>
/// 通过索引赋值,索引从1开始
/// </summary>
/// <param name="x">行</param>
/// <param name="y">列</param>
/// <param name="value"></param>
public void SetValue(int x, int y, string value)
{
worksheet.Cells[x, y].Value = value;//直接指定行列数进行赋值
} /// <summary>
/// 单元格赋值
/// </summary>
/// <param name="cell">单元格,如:A1</param>
/// <param name="value"></param>
public void SetValue(string cell, string value)
{
worksheet.Cells[cell].Value = value;//直接指定单元格进行赋值
} /// <summary>
/// 设置样式
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="isWrapText">是否换行</param>
/// <param name="horizontal">水平格式</param>
/// <param name="vertical">垂直格式</param>
/// <param name="isBold">是否粗体</param>
/// <param name="size">文字大小</param>
/// <param name="height">行高</param>
/// <param name="isShowGridLines">是否显示网格线</param>
public void SetStyle(int x, int y, bool isWrapText = true, ExcelHorizontalAlignment horizontal = ExcelHorizontalAlignment.Center, ExcelVerticalAlignment vertical = ExcelVerticalAlignment.Center, bool isBold = false, int size = 12, int height = 15, bool isShowGridLines = false)
{
//worksheet.Cells[x, y].Style.Numberformat.Format = "#,##0.00";//这是保留两位小数 worksheet.Cells[x, y].Style.HorizontalAlignment = horizontal;//水平居中
worksheet.Cells[x, y].Style.VerticalAlignment = vertical;//垂直居中
//worksheet.Cells[1, 4, 1, 5].Merge = true;//合并单元格
worksheet.Cells.Style.WrapText = isWrapText;//自动换行 worksheet.Cells[x, y].Style.Font.Bold = isBold;//字体为粗体
//worksheet.Cells[1, 1].Style.Font.Color.SetColor(Color.White);//字体颜色
//worksheet.Cells[1, 1].Style.Font.Name = "微软雅黑";//字体
worksheet.Cells[x, y].Style.Font.Size = size;//字体大小 //worksheet.Cells[1, 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
//worksheet.Cells[1, 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(128, 128, 128));//设置单元格背景色 worksheet.Cells[x, y].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.FromArgb(191, 191, 191));//设置单元格所有边框
worksheet.Cells[x, y].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;//单独设置单元格底部边框样式和颜色(上下左右均可分开设置)
worksheet.Cells[x, y].Style.Border.Bottom.Color.SetColor(Color.FromArgb(191, 191, 191)); //worksheet.Cells.Style.ShrinkToFit = true;//单元格自动适应大小
worksheet.Row(x).Height = height;//设置行高
//worksheet.Row(1).CustomHeight = true;//自动调整行高
//worksheet.Column(1).Width = 15;//设置列宽 worksheet.View.ShowGridLines = isShowGridLines;//去掉sheet的网格线
//worksheet.Cells.Style.Fill.PatternType = ExcelFillStyle.Solid;
//worksheet.Cells.Style.Fill.BackgroundColor.SetColor(Color.LightGray);//设置背景色
//worksheet.BackgroundImage.Image = Image.FromFile(@"firstbg.jpg");//设置背景图片
} public void SetMergeCell(int x1, int y1, int x2, int y2)
{
worksheet.Cells[x1, y1, x2, y2].Merge = true;//合并单元格
} public void TableToExcel(DataTable dt, string title)
{
DataColumnCollection columns = dt.Columns; int addIndex = 1; //表格标题
if (!string.IsNullOrEmpty(title))
{
addIndex = 2;
SetMergeCell(1, 1, 1, columns.Count);
SetStyle(1, 1, false, ExcelHorizontalAlignment.Center, ExcelVerticalAlignment.Center, true, 16, 25);
//worksheet.Cells.Merge(1, 1, 1, columns.Count);
SetValue(1, 1, title);
} //表头
if (columns.Count > 0)
{
int columnIndex = 1; foreach (DataColumn dc in columns)
{
SetStyle(addIndex, columnIndex);
SetValue(addIndex, columnIndex, dc.ColumnName);
columnIndex += 1;
}
} //数据
if (dt.Rows.Count > 0)
{
int rowIndex = 1 + addIndex; foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < columns.Count; i++)
{
SetStyle(rowIndex, i + 1);
SetValue(rowIndex, i + 1, dr[i].ToString());
} rowIndex += 1;
}
}
}
}
}

  demo

public void ExcelDemo02()
{
EpPlusHelper ep = new EpPlusHelper(Server.MapPath("/ExcelModel/model.xlsx")); ep.SetValue(3, 2, "龙富工业区");
ep.SetValue(3, 4, "2018.6.1 0:00-2018.6.30 24:00"); DataTable dt = new DataTable(); dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("Address", typeof(string));
dt.Columns.Add("平台", typeof(string));
dt.Columns.Add("DeviceType", typeof(string));
dt.Columns.Add("DeviceStatus", typeof(string));
dt.Columns.Add("Count", typeof(string));
dt.Columns.Add("Remark", typeof(string)); for (int i = 1; i < 10; i++)
{
DataRow dr = dt.NewRow(); dr["ID"] = i.ToString();
dr["Address"] = "地址" + i.ToString();
dr["平台"] = "平台" + i.ToString();
dr["DeviceType"] = "类型" + i.ToString();
dr["DeviceStatus"] = "状况" + i.ToString();
dr["Count"] = i.ToString();
dr["Remark"] = "备注" + i.ToString(); dt.Rows.Add(dr);
} int index = 6; foreach (DataRow dr in dt.Rows)
{
ep.SetValue(index, 1, Convert.ToString(dr["ID"]));
ep.SetStyle(index, 1); ep.SetValue(index, 2, Convert.ToString(dr["Address"]));
ep.SetStyle(index, 2); ep.SetValue(index, 3, Convert.ToString(dr["平台"]));
ep.SetStyle(index, 3); ep.SetValue(index, 4, Convert.ToString(dr["DeviceType"]));
ep.SetStyle(index, 4); ep.SetValue(index, 5, Convert.ToString(dr["DeviceStatus"]));
ep.SetStyle(index, 5); ep.SetValue(index, 6, Convert.ToString(dr["Count"]));
ep.SetStyle(index, 6); ep.SetValue(index, 7, Convert.ToString(dr["Remark"]));
ep.SetStyle(index, 7); index++;
} ep.SaveExcel(Response,"自定义名称");
}

  

.net mvc中epplus导出excel的更多相关文章

  1. C# NPOI导出Excel和EPPlus导出Excel比较

    系统中经常会使用导出Excel的功能. 之前使用的是NPOI,但是导出数据行数多就报内存溢出. 最近看到EPPlus可以用来导出Excel,就自己测了下两者导出上的差异. NPIO官网地址:http: ...

  2. C# NPOI导出Excel和EPPlus导出Excel

    转自:http://www.cnblogs.com/tanpeng/p/6155749.html 系统中经常会使用导出Excel的功能.之前使用的是NPOI,但是导出数据行数多就报内存溢出. 最近看到 ...

  3. C# 使用Epplus导出Excel [1]:导出固定列数据

    C# 使用Epplus导出Excel [1]:导出固定列数据 C# 使用Epplus导出Excel [2]:导出动态列数据 C# 使用Epplus导出Excel [3]:合并列连续相同数据 C# 使用 ...

  4. 从SQL Server中导入/导出Excel的基本方法(转)

    从sql server中导入/导出 excel 的基本方法 /*=========== 导入/导出 excel 的基本方法 ===========*/ 从excel文档中,导入数据到sql数据库中,很 ...

  5. html table表格导出excel的方法 html5 table导出Excel HTML用JS导出Excel的五种方法 html中table导出Excel 前端开发 将table内容导出到excel HTML table导出到Excel中的解决办法 js实现table导出Excel,保留table样式

    先上代码   <script type="text/javascript" language="javascript">   var idTmr; ...

  6. C# 使用Epplus导出Excel [5]:样式

    C# 使用Epplus导出Excel [1]:导出固定列数据 C# 使用Epplus导出Excel [2]:导出动态列数据 C# 使用Epplus导出Excel [3]:合并列连续相同数据 C# 使用 ...

  7. C# 使用Epplus导出Excel [4]:合并指定行

    C# 使用Epplus导出Excel [1]:导出固定列数据 C# 使用Epplus导出Excel [2]:导出动态列数据 C# 使用Epplus导出Excel [3]:合并列连续相同数据 C# 使用 ...

  8. C# 使用Epplus导出Excel [3]:合并列连续相同数据

    C# 使用Epplus导出Excel [1]:导出固定列数据 C# 使用Epplus导出Excel [2]:导出动态列数据 C# 使用Epplus导出Excel [3]:合并列连续相同数据 C# 使用 ...

  9. C# 使用Epplus导出Excel [2]:导出动态列数据

    C# 使用Epplus导出Excel [1]:导出固定列数据 C# 使用Epplus导出Excel [2]:导出动态列数据 C# 使用Epplus导出Excel [3]:合并列连续相同数据 C# 使用 ...

随机推荐

  1. python笔记21(面向对象课程三)

    今日内容 嵌套 特殊方法:__init__ type/isinstance/issubclass/super 异常处理 内容回顾 def login(): pass login() class Acc ...

  2. Go语言实现:【剑指offer】孩子们的游戏

    该题目来源于牛客网<剑指offer>专题. 每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此.HF作为牛客的资深元老,自然也准备了一些小游戏.其中,有个游戏是这样的 ...

  3. 《自拍教程6》打开Windows文件后缀

    如果你用的是Windows操作系统, 请把文件后缀名打开,千万别隐藏后缀名, 后续有各类 .py, .sh, .bat, .exe等不同文件, 需要你时刻关注文件后缀名. 如果是我看到我手下的测试人员 ...

  4. Mysql 字符问题

    先看一下mysql支持的字符范围 *数值类型:1.整形: 类型                               大小     范围                              ...

  5. C# checked unchecked

    static void CheckedUnCheckedDemo() { int i = int.MaxValue; try { //checked //{ // Console.WriteLine( ...

  6. css如何玩转有序无序列表项list样式

    在无序列表ul>li中,无线列表的标志是出现在各列表前面的圆点.在有序列表ol>li中,前面默认带有数字,如何修改列表前面的项目符号,只需要通过list-style调整就好,常见的符号有( ...

  7. Centos7内核版安装nginx环境问题及解决方法

    错误信息:./configure: error: C compiler cc is not found解决方案:yum -y install gcc gcc-c++ autoconf automake ...

  8. python——面向对象(4),单继承

    """class 类名(object<父类>)继承:子类继承父类.单继承:""" class A(object): " ...

  9. 《C++Primer》第五版习题答案--第五章【学习笔记】

    <C++Primer>第五版习题答案--第五章[学习笔记] ps:答案是个人在学习过程中书写,可能存在错漏之处,仅作参考. 作者:cosefy Date: 2020/1/15 第五章:语句 ...

  10. 『后缀自动机入门 SuffixAutomaton』

    本文的图片材料多数来自\(\mathrm{hihocoder}\)中详尽的\(SAM\)介绍,文字总结为原创内容. 确定性有限状态自动机 DFA 首先我们要定义确定性有限状态自动机\(\mathrm{ ...