You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
BookingHeChuan/Myshipping.Report/Controllers/ReportController.cs

120 lines
4.0 KiB
C#

using FastReport.Export.OoXML;
using FastReport.Export.Pdf;
using Myshipping.Report.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Myshipping.Report.DB;
using Myshipping.Application.Entity;
using System.Text;
namespace Myshipping.Report.Controllers
{
public class ReportController : Controller
{
private SqlSugar.SqlSugarClient sqlSugarClient;
public ReportController()
{
sqlSugarClient = new SqlSugar.SqlSugarClient(new BookingConnectionConfig());
}
/// <summary>
/// 生成订舱报表结果
/// </summary>
/// <param name="templateFile">模板文件路径</param>
/// <param name="bookingId">订舱ID</param>
/// <param name="type">类型1pdf、2xlsx</param>
/// <returns></returns>
[HttpGet]
public ActionResult BookingReport(string templateFile, long bookingId, int type = 1)
{
var resp = new RespCommonData();
if (System.IO.File.Exists(templateFile))
{
var savePath = ConfigurationManager.AppSettings["ReportFileSavePath"];
if (string.IsNullOrEmpty(savePath)) //未配置保存路径时,使用当前目录
{
savePath = Server.MapPath("~/ReportFiles");
}
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
//生成报表
FastReport.Report report = new FastReport.Report();
report.Load(templateFile);
foreach (FastReport.Data.JsonConnection.JsonDataSourceConnection conn in report.Dictionary.Connections)
{
if (conn.Name == "booking_order")
{
conn.ConnectionString = $"Json={Convert.ToBase64String(Encoding.UTF8.GetBytes(GetBookingJson(bookingId)))};Encoding=utf-8";
}
}
report.Prepare();
if (type == 1) //pdf
{
var saveFile = Path.Combine(savePath, $"{bookingId}_{DateTime.Now.Ticks}.pdf");
PDFExport pdfExport = new PDFExport();
pdfExport.Export(report, saveFile);
resp.Success = true;
resp.Message = "生成成功";
resp.Data = saveFile;
}
else if (type == 2) //
{
var saveFile = Path.Combine(savePath, $"{bookingId}_{DateTime.Now.Ticks}.xlsx");
Excel2007Export excelExport = new Excel2007Export();
excelExport.Export(report, saveFile);
resp.Success = true;
resp.Message = "生成成功";
resp.Data = saveFile;
}
else
{
resp.Success = false;
resp.Message = "类型参数不正确";
}
return Json(resp, JsonRequestBehavior.AllowGet);
}
else
{
resp.Success = false;
resp.Message = "未找到模板文件";
}
return Json(resp, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult BookingReportJson(long bookingId)
{
return Content(GetBookingJson(bookingId));
}
[NonAction]
private string GetBookingJson(long bookingId)
{
var order = sqlSugarClient.Queryable<BookingOrder>().First(x => x.Id == bookingId);
var ctns = sqlSugarClient.Queryable<BookingCtn>().Where(x => x.BILLID == bookingId).ToList();
return JsonConvert.SerializeObject(new
{
order = order,
ctns = ctns
});
}
}
}