准备工作:
1.处理模板 要替换的内容 最好与数据库字段对应 一般导出都是跟 查看详情的内容 有很大相同的部分
2.准备一个 映射模板内容 的 dto对象 为什么?就是怕 不完全跟数据库内容对应 有一些处理 比如 导出的内容 A 可能是数据库 字段 a+b的和
开始工作:
1. 从数据库获取资源 一般就是 Deatil的详情数据 查看详情接口所提供的数据
2. 映射到 准备的dto对象中 处理一些 整合资源
3. 加载模板资源 替换资源
4.通知浏览器下载
代码:
/// <summary>
/// 根据数据源 导出小区
/// </summary>
/// <returns></returns>
public void GetExcelBySearchId(string Id)
{
//1 得到导出数据资源
var data = this.SearchDetail(Id);
if (data == null) throw new CustomException("没有可以导出的数据");
//2 是否需要处理资源 比如一些内容整合 映射到占位数据对象
var RtnExcelDto = data.MapTo<RtnExcelDto>();
//如果有一些特殊处理 比如说 需要字段求和 就在这一步
//3 Excel模板流加载 并替换站位符
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Export\\Template\\小区导出信息模板.xlsx";
using (FileStream stream = File.OpenRead(filepath))
{
IWorkbook workbook = WorkbookFactory.Create(stream);
ISheet sheet = workbook.GetSheetAt(0);//得到里面第一个sheet
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum;
int rowCount = sheet.LastRowNum;
//var strProject = ""; 换行的话 就叫\n
//int index = 1;
//projectList.ForEach(t => {
// strProject += index + ":" + t.Remark+ "\n";
// index++;
//});
RtnExcelDto.Project = strProject;
for (int i = 0; i < rowCount; i++)
{
IRow row = sheet.GetRow(i);
for (int j = 0; j < cellCount; j++)
{
NPOI.SS.UserModel.ICell cell = row.GetCell(j);
ReplaceExcelKey(RtnExcelDto, cell);
}
}
//填充完毕 下载 为防止重名 先弄好文件后缀
var filename = "小区导出" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + ".xlsx";
//创建文件流
MemoryStream bookStream = new MemoryStream();
//文件写入流(向流中写入字节序列)
workbook.Write(bookStream);
//输出之前调用Seek(偏移量,游标位置) 把0位置指定为开始位置
//bookStream.Seek(0, SeekOrigin.Begin);
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", filename));
System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
System.Web.HttpContext.Current.Response.Charset = "gb2312";
System.Web.HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
System.Web.HttpContext.Current.Response.BinaryWrite(bookStream.GetBuffer());
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();
}
}
private void ReplaceExcelKey<T>(T etity, NPOI.SS.UserModel.ICell cell)
{
Type entityType = typeof(T);
PropertyInfo[] properties = entityType.GetProperties();
if (cell != null)
{
var text = "";
if (cell.CellType == CellType.String)//这里根据不同的类型进行不同的处理
{
text = cell.ToString();
}
if (text != "")
{
foreach (var p in properties)
{
string propteryName = "[" + p.Name + "]"; //这里就要看 替换匹配的规则了 看 是 [] 还是 {} 还是 什么符号
object value = p.GetValue(etity);
if (value == null)
{
value = "";
}
if (text.Contains(propteryName))
{
var v = value.ToString();
text = text.Replace(propteryName, v);
}
cell.SetCellValue(text);
}
}
}
}