asp.net core导出导入excel
asp.net core导出导入excel
使用NPOI导入导出excel,已经封装好Action可以直接调用
导出
效果图
使用方法
定义导出实体
class Student
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsBanZhang { get; set; }
public static IEnumerable<Student> GetStudents()
{
return new List<Student>
{
new Student{Name="小强",Id=1,IsBanZhang=false},
new Student{Name="小文",Id=2,IsBanZhang=true},
new Student{Name="小黄",Id=3,IsBanZhang=false},
new Student{Name="小刚",Id=3,IsBanZhang=false},
};
}
}
导出Action
public IActionResult DownExcel()
{
var list = Student.GetStudents();
var excelHeper = new ExcelHelper();
var config = new List<ExcelGridModel> {
new ExcelGridModel{name="Id",label="学号", align="left",},
new ExcelGridModel{name="Name",label="姓名", align="left",},
new ExcelGridModel{name="IsBanZhang",label="是否班长", align="left",},
};
var fileName = "a.excel";
return excelHeper.ExcelDownload(list, config, fileName);
}
主要代码
导入导出代码
/// <summary>
/// 描 述:NPOI Excel DataTable操作类
/// </summary>
public class ExcelHelper
{
#region Excel导出方法 ExcelDownload
/// <summary>
/// Excel导出下载
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="list">数据源</param>
/// <param name="columnJson">导出列</param>
/// <param name="fileName">下载文件名称</param>
public ActionResult ExcelDownload<T>(IEnumerable<T> list, IEnumerable<ExcelGridModel> columnList, string fileName)
{
var excelConfig = ConvertExcelGridModelToConfig(columnList, fileName);
var rowData = list.ToDataTable(columnList.Select(i => i.name));
var stream = ExportMemoryStream(rowData, excelConfig);
return new FileStreamResult(stream, MIMEType.xls) { FileDownloadName = JointXls(fileName) };
}
/// <summary>
/// Excel导出下载
/// </summary>
/// <param name="dtSource">DataTable数据源</param>
/// <param name="excelConfig">导出设置包含文件名、标题、列设置</param>
public ActionResult ExcelDownload(DataTable dtSource, IEnumerable<ExcelGridModel> columnList, string fileName)
{
var excelConfig = ConvertExcelGridModelToConfig(columnList, fileName);
var stream = ExportMemoryStream(dtSource, excelConfig);
return new FileStreamResult(stream, MIMEType.xls) { FileDownloadName = JointXls(fileName) };
}
/// <summary>
/// Excel导出下载
/// </summary>
/// <param name="dtSource">DataTable数据源</param>
/// <param name="excelConfig">导出设置包含文件名、标题、列设置</param>
public ActionResult ExcelDownload(DataTable dtSource, ExcelConfig excelConfig, string fileName)
{
var stream = ExportMemoryStream(dtSource, excelConfig);
return new FileStreamResult(stream, MIMEType.xls) { FileDownloadName = JointXls(fileName) };
}
#endregion Excel导出方法 ExcelDownload
#region DataTable导出到Excel文件excelConfig中FileName设置为全路径
/// <summary>
/// DataTable导出到Excel文件 Export()
/// </summary>
/// <param name="dtSource">DataTable数据源</param>
/// <param name="excelConfig">导出设置包含文件名、标题、列设置</param>
public string ExcelExportToFile(DataTable dtSource, ExcelConfig excelConfig, string fileName)
{
fileName = JointXls(fileName);
using (MemoryStream ms = ExportMemoryStream(dtSource, excelConfig))
{
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);
fs.Flush();
}
}
return fileName;
}
#endregion DataTable导出到Excel文件excelConfig中FileName设置为全路径
#region DataTable导出到Excel的MemoryStream
/// <summary>
/// DataTable导出到Excel的MemoryStream Export()
/// </summary>
/// <param name="dtSource">DataTable数据源</param>
/// <param name="excelConfig">导出设置包含文件名、标题、列设置</param>
public MemoryStream ExportMemoryStream(DataTable dtSource, ExcelConfig excelConfig)
{
var columnEntity = excelConfig.ColumnEntity;
if (columnEntity == null || columnEntity.Count == 0)
{
if (columnEntity == null)
{
columnEntity = new List<ColumnModel>();
}
foreach (DataColumn dc in dtSource.Columns)
{
columnEntity.Add(new ColumnModel
{
Alignment = "center",
Column = dc.ColumnName,
ExcelColumn = dc.ColumnName
});
}
}
else
{
int colint = 0;
for (int i = 0; i < dtSource.Columns.Count;)
{
DataColumn column = dtSource.Columns[i];
if (excelConfig.ColumnEntity[colint].Column != column.ColumnName)
{
dtSource.Columns.Remove(column.ColumnName);
}
else
{
i++;
if (colint < excelConfig.ColumnEntity.Count - 1)
{
colint++;
}
}
}
}
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet();
#region 右击文件 属性信息
{
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "NPOI";
workbook.DocumentSummaryInformation = dsi;
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Author = ""; //填加xls文件作者信息
si.ApplicationName = ""; //填加xls文件创建程序信息
si.LastAuthor = ""; //填加xls文件最后保存者信息
si.Comments = ""; //填加xls文件作者信息
si.Title = ""; //填加xls文件标题信息
si.Subject = "";//填加文件主题信息
si.CreateDateTime = System.DateTime.Now;
workbook.SummaryInformation = si;
}
#endregion 右击文件 属性信息
#region 设置标题样式
ICellStyle headStyle = workbook.CreateCellStyle();
int[] arrColWidth = new int[dtSource.Columns.Count];
string[] arrColName = new string[dtSource.Columns.Count];//列名
ICellStyle[] arryColumStyle = new ICellStyle[dtSource.Columns.Count];//样式表
headStyle.Alignment = HorizontalAlignment.Center; // ------------------
if (excelConfig.Background != new Color())
{
if (excelConfig.Background != new Color())
{
headStyle.FillPattern = FillPattern.SolidForeground;
headStyle.FillForegroundColor = GetXLColour(workbook, excelConfig.Background);
}
}
IFont font = workbook.CreateFont();
font.FontHeightInPoints = excelConfig.TitlePoint;
if (excelConfig.ForeColor != new Color())
{
font.Color = GetXLColour(workbook, excelConfig.ForeColor);
}
font.Boldweight = 700;
headStyle.SetFont(font);
#endregion 设置标题样式
#region 列头及样式
ICellStyle cHeadStyle = workbook.CreateCellStyle();
cHeadStyle.Alignment = HorizontalAlignment.Center; // ------------------
IFont cfont = workbook.CreateFont();
cfont.FontHeightInPoints = excelConfig.HeadPoint;
cHeadStyle.SetFont(cfont);
#endregion 列头及样式
#region 设置内容单元格样式
foreach (DataColumn item in dtSource.Columns)
{
ICellStyle columnStyle = workbook.CreateCellStyle();
columnStyle.Alignment = HorizontalAlignment.Center;
arrColWidth[item.Ordinal] = Encoding.UTF8.GetBytes(item.ColumnName.ToString()).Length;
arrColName[item.Ordinal] = item.ColumnName.ToString();
if (excelConfig.ColumnEntity != null)
{
ColumnModel columnentity = excelConfig.ColumnEntity.Find(t => t.Column == item.ColumnName);
if (columnentity != null)
{
arrColName[item.Ordinal] = columnentity.ExcelColumn;
if (columnentity.Width != 0)
{
arrColWidth[item.Ordinal] = columnentity.Width;
}
if (columnentity.Background != new Color())
{
if (columnentity.Background != new Color())
{
columnStyle.FillPattern = FillPattern.SolidForeground;
columnStyle.FillForegroundColor = GetXLColour(workbook, columnentity.Background);
}
}
if (columnentity.Font != null || columnentity.Point != 0 || columnentity.ForeColor != new Color())
{
IFont columnFont = workbook.CreateFont();
columnFont.FontHeightInPoints = 10;
if (columnentity.Font != null)
{
columnFont.FontName = columnentity.Font;
}
if (columnentity.Point != 0)
{
columnFont.FontHeightInPoints = columnentity.Point;
}
if (columnentity.ForeColor != new Color())
{
columnFont.Color = GetXLColour(workbook, columnentity.ForeColor);
}
columnStyle.SetFont(font);
}
columnStyle.Alignment = getAlignment(columnentity.Alignment);
}
}
arryColumStyle[item.Ordinal] = columnStyle;
}
if (excelConfig.IsAllSizeColumn)
{
#region 根据列中最长列的长度取得列宽