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);
});
}