1. 程式人生 > >Asp.net Core導出Excel

Asp.net Core導出Excel

名稱 string 需求 mvc cep param cti 了吧 collect

本篇文章是在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;
}

Asp.net Core導出Excel