使用C#MVC中的Eppplus将数据表导出到XLSX

问题描述 投票:0回答:1

我正在尝试在我的MVC应用程序中使用epplus将数据表导出到excel。这是我的代码,但不是从我的数据表中导出数据,而是我的excel文件显示的是

容量----计数256 --------- 206

这是我正在使用的代码:

public IActionResult ToExcelWeGo()
{
  string workbookName = null;
  var data = _context.testtable.FromSqlRaw("Select * from hiringInfo").ToList();
  DataTable dt = new DataTable();
  dt = ObjectToData(data);
  using (ExcelPackage pack = new ExcelPackage())
  {
    ExcelWorksheet objWorksheet = pck.WOrkbook.WOrksheets.Add("Sheet1");
    objWorksheet.Name = "Test";
    workbookName = "Test Workbook.xlsx";
    var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    var fileStream = new MemoryStream();
    pck.SaveAs(fileStream);
    fileStream.Position = 0;
    var fsr = new FileStreamResult(fileStream, contentType);
    fsr.FileDownloadName = workbookName;
    return fsr;
  }
}
public static DataTable ObjectToData(object o)
{
  DataTable dt = new DataTable("OutputData");
  DataRow dr = dt.NewRow();
  dt.Rows.Add(dr);
  o.GetType().GetProperties().ToList().ForEach(f =>
  {
    try
    {
      f.GetValue(o, null);
      dt.Columns.Add(f.Name, f.PropertyType);
      dt.Rows[0][f.Name] = f.GetValue(o, null);
    }
    catch {}
  });
  return dt;
}

为什么我的数据表没有按预期显示?

c# asp.net-mvc epplus
1个回答
1
投票

创建DataExporter类:

     public static class DataExporter
    {

        static DataTable dtExcel = new DataTable();
        private static void ReadData(string query)
        {
            //Get Datatable here by query or you can use LINQtoDataTable
            dtExcel = DBQuery.GetDataTableByQuery(query);
        }

        private static Byte[] PrepareByte(DataTable dt)
        {
            Byte[] bytes;

            int colCount = dt.Columns.Count;

            ExcelPackage excel = new ExcelPackage();
            var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
            workSheet.DefaultRowHeight = 12;
            workSheet.Row(1).Height = 20;
            workSheet.Row(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
            workSheet.Row(1).Style.Font.Bold = true;

            for (int looper = 1; looper <= colCount; looper++)
                workSheet.Cells[1, looper].Value = dt.Columns[looper - 1].ColumnName;

            for (int looper = 1; looper <= colCount; looper++)
            {
                workSheet.Cells[1, looper].Style.Border.Top.Style = ExcelBorderStyle.Thin;
                workSheet.Cells[1, looper].Style.Border.Left.Style = ExcelBorderStyle.Thin;
                workSheet.Cells[1, looper].Style.Border.Right.Style = ExcelBorderStyle.Thin;
                workSheet.Cells[1, looper].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
            }

            for (int rowNo = 0; rowNo < dt.Rows.Count; rowNo++)
            {
                for (int colNo = 0; colNo < colCount; colNo++)
                    workSheet.Cells[rowNo + 2, colNo + 1].Value = dt.Rows[rowNo][colNo];

                for (int innerLooper = 1; innerLooper <= colCount; innerLooper++)
                {
                    workSheet.Cells[rowNo + 2, innerLooper].Style.Border.Top.Style = ExcelBorderStyle.Thin;
                    workSheet.Cells[rowNo + 2, innerLooper].Style.Border.Left.Style = ExcelBorderStyle.Thin;
                    workSheet.Cells[rowNo + 2, innerLooper].Style.Border.Right.Style = ExcelBorderStyle.Thin;
                    workSheet.Cells[rowNo + 2, innerLooper].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                }
            }

            for (int looper = 1; looper <= colCount; looper++)
                workSheet.Column(looper).AutoFit();

            bytes = excel.GetAsByteArray();

            return bytes;
        }

        public static Byte[] GetBytes(string query)
        {
            Byte[] bytes;
            ReadData(query);
            bytes = PrepareByte(dtExcel);
            return bytes;
        }


        public static Byte[] GetBytes(DataTable dt)
        {
            Byte[] bytes;
            bytes = PrepareByte(dt);
            return bytes;
        }
    }

现在从任何页面开始,只需调用DataExporter类并传递数据表即可。希望它会工作:

            DataTable dt = new DataTable();
            dt.Columns.Add("EMP_ID", typeof(string));
            dt.Columns.Add("EMP_NAME", typeof(string));
            dt.Columns.Add("DEPARTMENT_NAME", typeof(string));
            dt.Columns.Add("DESIGNATION", typeof(string));
            dt.Columns.Add("BRANCH", typeof(string));
            dt.Columns.Add("AMOUNT", typeof(double));

            Byte[] bytes = DataExporter.GetBytes(dt);

            Response.ClearHeaders();
            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-length", bytes.Length.ToString());
            Response.AddHeader("content-disposition", "attachment; filename=AddDataUpload.xlsx");
            Response.OutputStream.Write(bytes, 0, bytes.Length);
            Response.Flush();
            HttpContext.Current.ApplicationInstance.CompleteRequest();
© www.soinside.com 2019 - 2024. All rights reserved.