使用EPPlus实现execel导出功能

1、后台生成execel

public ActionResult DataExport()
{
	using (MiniPoco.Database db = new MiniPoco.Database())
	{
		try
		{
			string str2 = "订单.xlsx";
			string path = Server.MapPath("~/Upload/DownloadExcal/User/");
			if (!Directory.Exists(path))
			{
				Directory.CreateDirectory(path);
			}

			string fileName = Path.Combine(path, str2);
			FileInfo newFile = new FileInfo(fileName);
			if (newFile.Exists)
			{
				newFile.Delete();
				newFile = new FileInfo(fileName);
			}
			
			string sql = string.Format(@"select A.* from Order A",);
		  
			DataTable dt = db.GetDataTable(sql);
			using (ExcelPackage package = new ExcelPackage(newFile))
			{
				ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("table");
				worksheet.Cells[1, 1].Value = "序号";
				worksheet.Cells[1, 2].Value = "分厂名称";
				worksheet.Cells[1, 3].Value = "客户名称";
				worksheet.Cells[1, 4].Value = "申请日期";
				worksheet.Cells[1, 5].Value = "申请类型";
				worksheet.Cells[1, 6].Value = "品种";
				worksheet.Cells[1, 7].Value = "规格";
				worksheet.Cells[1, 8].Value = "订单单号";
				worksheet.Cells[1, 9].Value = "米数";
				worksheet.Cells[1, 10].Value = "自带助剂信息";
				worksheet.Cells[1, 11].Value = "整理价格";
			  
				for (int i = 0; i < dt.Rows.Count; i++)
				{
					worksheet.Cells[i + 2, 1].Value = i + 1;
					worksheet.Cells[i + 2, 2].Value = dt.Rows[i]["FACTORYNAME"].ToString();
					worksheet.Cells[i + 2, 3].Value = dt.Rows[i]["CUSTOMERNAME"].ToString();
					worksheet.Cells[i + 2, 4].Value = Convert.ToDateTime(dt.Rows[i]["ADDDATE"].ToString()).ToString("yyyy-MM-dd");
					worksheet.Cells[i + 2, 5].Value = dt.Rows[i]["IS_KEEPONRECORD"].ToString();
					worksheet.Cells[i + 2, 6].Value = dt.Rows[i]["PRODUCTNAME"].ToString();
					worksheet.Cells[i + 2, 7].Value = dt.Rows[i]["SPECIFICATIONS"].ToString();
					worksheet.Cells[i + 2, 8].Value = dt.Rows[i]["ORDERNO"].ToString();
					worksheet.Cells[i + 2, 9].Value = dt.Rows[i]["TOTAL_METER"].ToString();
					worksheet.Cells[i + 2, 10].Value = dt.Rows[i]["BYO_AUXILIARY_INFO"].ToString();
					worksheet.Cells[i + 2, 11].Value = dt.Rows[i]["FIX_PRICE"].ToString();
				}
				package.Save();
			}
			Hashtable ht = new Hashtable();
			ht["Message"] = "已导出成功";
			ht["Url"] = "/Upload/DownloadExcal/User/" + str2;
			return Content(ht.ToJson());
		}
		catch (Exception ex)
		{
			return Content(new JsonMessage { Success = false, Code = "-1", Message = "操作失败:" + ex.Message }.ToString());
		}
	}
}

2、前端js方法

function btn_export() {
	var data={};
	AjaxJson("/Order/DataExport", data, function (rs) {
		window.location.href = rs.Url;
		parent.layer.msg(rs.Message);
	});
}

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页