Asp.net Core导出Excel

倾然丶 夕夏残阳落幕 提交于 2020-12-11 13:39:46

本篇文章是在MVC设计模式下,基于windows系统的Excel导出

1.前台的实现不用我多说了吧,加一个a标签链接地址跳到它所调用的方法里面,可以根据当前页面的查询条件去传值,从而查询出你想要的数据然后导出

下面我们就直接来看控制器里的方法和对数据的处理

/// <summary>
/// 导出数据
/// </summary>
/// <returns></returns>
public void ExportData(int pageIndex, int limit, string name, string startVisitTime, string endVisitTime, string addUser)
{
int count = 0;
string fileExt = ".xls";
try
{
if (pageIndex != 0)
{
pageIndex = 0;
}
List<VisitsRecordDto> visitRecord = visitRecordReportInterface.GetVisitRecordList(pageIndex, limit, name, startVisitTime, endVisitTime, addUser, out count);
Dictionary<string, string> columnNames = new Dictionary<string, string> {
{ "AddUser","添加人" },
{ "VisitsTime", "拜访日期" },
{ "CustomerName", "客户名称" },
{ "LinkMan", "联系人" },
{ "CustomerNeed", "客户需求" },
{ "ExistingProblem", "存在的问题" },
{ "SuccessEffect", "达成的效果" },
{ "NextPlan", "下一步跟进计划" },
{ "VisitEvalaute", "拜访评价" },
{ "Score", "拜访评分" }
};
byte[] stream = Common.ExcelHelper.CollectionsToExcel<VisitsRecordDto>(visitRecord, fileExt, columnNames);
//获取文件的ContentType
var provider = new FileExtensionContentTypeProvider();
var memi = provider.Mappings[fileExt];
Response.ContentType = memi;
Encoding utf8 = Encoding.UTF8;
//将已经解码的字符再次进行编码.
string encode = HttpUtility.UrlEncode("拜访总结报表.xls", utf8).ToUpper();

Response.Headers.Add("Content-Disposition", "attachment;filename=" + encode);
Response.Body.Write(stream);
Response.Body.Flush();
Response.Body.Close();
}
catch (Exception ex)
{

}
}

3.将Excel转换为Datatable

/// <summary>
/// 集合导出Excel
/// </summary>
/// <param name="list">集合</param>
/// <param name="fileExt">文件后缀</param>
/// <param name="columnNames">列名转换</param>
/// <param name="dicOnly">部分转换</param>
/// <returns></returns>
public static byte[] CollectionsToExcel<T>(List<T> list, string fileExt, Dictionary<string, string> columnNames,bool dicOnly=false)
{
if (list.Count() <= 0)
{
return null;
}
DataTable dt = CollectionsToDataTable<T>(list);
IWorkbook workbook;
ICellStyle cellStyle;
ICellStyle headerCellStyle;
if (fileExt == ".xlsx")
{
workbook = new XSSFWorkbook();
cellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
headerCellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
}
else if (fileExt == ".xls")
{
workbook = new HSSFWorkbook();
cellStyle = (HSSFCellStyle)workbook.CreateCellStyle();
headerCellStyle = (HSSFCellStyle)workbook.CreateCellStyle();
}
else
{
workbook = null;
cellStyle = (HSSFCellStyle)workbook.CreateCellStyle();
headerCellStyle = (HSSFCellStyle)workbook.CreateCellStyle();
return null;
}

ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);

IFont font = workbook.CreateFont();
font.FontName = "宋体";
font.FontHeightInPoints = 9;

cellStyle.Alignment = HorizontalAlignment.Left;
cellStyle.VerticalAlignment = VerticalAlignment.Center;
cellStyle.BorderBottom = BorderStyle.Thin;
cellStyle.BorderTop = BorderStyle.Thin;
cellStyle.BorderLeft = BorderStyle.Thin;
cellStyle.BorderRight = BorderStyle.Thin;
cellStyle.SetFont(font);

IFont headerFont = workbook.CreateFont();
headerFont.FontName = "宋体";
headerFont.FontHeightInPoints = 9;
headerFont.Boldweight = short.MaxValue;
headerCellStyle.Alignment = HorizontalAlignment.Center;
headerCellStyle.VerticalAlignment = VerticalAlignment.Center;
headerCellStyle.FillForegroundColor = 22;
headerCellStyle.FillPattern = FillPattern.SolidForeground;
headerCellStyle.BorderBottom = BorderStyle.Thin;
headerCellStyle.BorderTop = BorderStyle.Medium;
headerCellStyle.BorderLeft = BorderStyle.Thin;
headerCellStyle.BorderRight = BorderStyle.Thin;
headerCellStyle.SetFont(headerFont);

if (dicOnly == true)
{
for (int i = dt.Columns.Count - 1; i >= 0; i--)
{
string rowName = dt.Columns[i].ColumnName;
if (!columnNames.Keys.Contains(rowName))
{
dt.Columns.RemoveAt(i);
}
}
}

//表头
IRow row = sheet.CreateRow(0);
row.HeightInPoints = 20;
for (int i = 0; i < dt.Columns.Count; i++)
{
sheet.SetColumnWidth(i, 25 * 256);
ICell cell = row.CreateCell(i);
cell.CellStyle = headerCellStyle;
string rowName = dt.Columns[i].ColumnName;
if (columnNames.Keys.Contains(rowName))
{
cell.SetCellValue(columnNames[rowName]);
}
else
{
cell.SetCellValue(dt.Columns[i].ColumnName);
}
}

//数据
for (int i = 0; i < dt.Rows.Count; i++)
{
//将数据从表格第二行开始填入
IRow row1 = sheet.CreateRow(i + 1);
row1.HeightInPoints = 15;
for (int j = 0; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
cell.CellStyle = cellStyle;
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}

//转为字节数组
MemoryStream stream = new MemoryStream();
workbook.Write(stream);
var buf = stream.ToArray();
workbook.Close();
stream.Close();
stream.Dispose();
return buf;
}

将集合转换为datatable

/// <summary>
/// 将集合转为DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static DataTable CollectionsToDataTable<T>(List<T> list)
{
Type type = typeof(T);
DataTable dt = new DataTable();
foreach (PropertyInfo item in type.GetProperties())
{
dt.Columns.Add(item.Name, typeof(string));
}
foreach (T item in list)
{
DataRow Row = dt.NewRow();
foreach (PropertyInfo propertyInfo in type.GetProperties())
{
if (propertyInfo.PropertyType == typeof(DateTime?))
{
Row[propertyInfo.Name] = propertyInfo.GetValue(item) == null ? "" : DateTime.Parse(propertyInfo.GetValue(item).ToString()).ToString("yyyy-MM-dd");
}
else
{
Row[propertyInfo.Name] = propertyInfo.GetValue(item);
}
}
dt.Rows.Add(Row);
}
return dt;
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!