Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#从类导出到Excel_C#_Excel_Reference_Httpcontext_System.web - Fatal编程技术网

C#从类导出到Excel

C#从类导出到Excel,c#,excel,reference,httpcontext,system.web,C#,Excel,Reference,Httpcontext,System.web,下面是一个将数据从表/存储过程导出到Excel的示例。 唯一的区别是,因为我有一个Angular/MVC项目,所以我在类中使用此代码。在“Export_To_Excel()”方法中,有 Response.Clear();以及其他响应方法。但我得到了一个错误,“响应在当前上下文中不存在。”所以我尝试更改为完全限定引用: HttpContext.Current.Response或 System.Web.HttpContext.Current.Response 但现在我得到一个错误,“一个对象引用没

下面是一个将数据从表/存储过程导出到Excel的示例。

唯一的区别是,因为我有一个Angular/MVC项目,所以我在类中使用此代码。在“Export_To_Excel()”方法中,有 Response.Clear();以及其他响应方法。但我得到了一个错误,“响应在当前上下文中不存在。”所以我尝试更改为完全限定引用: HttpContext.Current.Response或 System.Web.HttpContext.Current.Response 但现在我得到一个错误,“一个对象引用没有设置为对象的实例”

请指导怎么做?这是我在cs文件中的完整代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ClosedXML.Excel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyProject.DAL
{
    public class CreateWorkBook
    {
        private DataTable getAllEmployeesList()
        {

            using (SqlConnection con = Connection.GetConnection())
            {
                using (SqlCommand cmd = new SqlCommand(@"SELECT * FROM Employee ORDER BY ID;"))
                {
                    using (SqlDataAdapter da = new SqlDataAdapter())
                    {
                        DataTable dt = new DataTable();
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = con;
                        da.SelectCommand = cmd;
                        da.Fill(dt);
                        return dt;
                    }
                }
            }
        }

        private DataTable getAllEmployeesOrderList()
        {

            using (SqlConnection con = Connection.GetConnection())
            {
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM OrderDetails ORDER BY Order_ID;"))
                {
                    using (SqlDataAdapter da = new SqlDataAdapter())
                    {
                        DataTable dt = new DataTable();
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = con;
                        da.SelectCommand = cmd;
                        da.Fill(dt);
                        return dt;
                    }
                }
            }
        }

        public DataSet getDataSetExportToExcel()
        {
            DataSet ds = new DataSet();
            DataTable dtEmp = new DataTable("Employee");
            dtEmp = getAllEmployeesList();

            DataTable dtEmpOrder = new DataTable("Order List");
            dtEmpOrder = getAllEmployeesOrderList();
            ds.Tables.Add(dtEmp);
            ds.Tables.Add(dtEmpOrder);
            return ds;
        }
        public string SetToExport(string channel, string assets )
        {
            string status = Export_To_Excel();
            return "success";
        }
        protected string Export_To_Excel()
        {
            try
            {
                DataSet ds = getDataSetExportToExcel();
                using (XLWorkbook wb = new XLWorkbook())
                {
                    wb.Worksheets.Add(ds);
                    wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    wb.Style.Font.Bold = true;
// Error here – 
//An object reference not set to an instance of Object  
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.Buffer = true;
                    System.Web.HttpContext.Current.Response.Charset = "";
                    System.Web.HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename= SubmissionForm.xlsx");
                    using (MemoryStream MyMemoryStream = new MemoryStream())
                    {
                        wb.SaveAs(MyMemoryStream);
                        MyMemoryStream.WriteTo(System.Web.HttpContext.Current.Response.OutputStream);
                        System.Web.HttpContext.Current.Response.Flush();
                        System.Web.HttpContext.Current.Response.End();
                    }
                }

                return "success";
            }
            catch (Exception e)
            {
                throw e;
                //return "Export to Excel failed";
            }

        }

        }
}

只是不要使用下面与Excel导出操作无关的注释代码

//HttpContext.Current.Response.Clear();
//HttpContext.Current.Response.Buffer = true;
//System.Web.HttpContext.Current.Response.Charset = "";
//System.Web.HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
//System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename= SubmissionForm.xlsx");

using (MemoryStream MyMemoryStream = new MemoryStream())
{
    wb.SaveAs(MyMemoryStream);
    //you need to replace below line according to your need. **
    //MyMemoryStream.WriteTo(System.Web.HttpContext.Current.Response.OutputStream);
    //System.Web.HttpContext.Current.Response.Flush();
    //System.Web.HttpContext.Current.Response.End();
}

**如果不知道您的项目结构和您的意图,就不可能告诉您下载/保存此文件的正确方法。

正如@Scott在评论中提到的,您应该将其分解为几个小问题

  • 首先创建代码以成功生成excel文件。这将返回一个
    字节[]
    。为了简化工作,您可以创建一个控制台应用程序,首先将文件本地保存到PC,然后测试并确保其正常工作
  • 第1部分开始工作后,将生成
    字节[]
    的代码复制到web项目中。然后,您只需要了解如何将MVC中的文件下载到客户端
  • 下面的代码可能会有所帮助

        // CreateWorkBook class
        public byte[] Export_To_Excel()
        {           
            DataSet ds = getDataSetExportToExcel();
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(ds);
                wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                wb.Style.Font.Bold = true;
    
                using (MemoryStream myMemoryStream = new MemoryStream())
                {
                    wb.SaveAs(myMemoryStream);
    
                    // return memory stream as byte array
                    return myMemoryStream.ToArray();
                }
            }
        }
    
    然后在控制器中,您可以使用
    FileResult
    返回excel文件。下面是一个如何在MVC控制器中实现的示例

    // your MVC controller
    [HttpGet]
    public FileResult DownloadExcel()
    {
        var createExcel = new CreateWorkBook();
        byte[] excelFile = null;
        try
        {
            excelFile = createExcel.Export_To_Excel();
        }
        catch (Exception ex)
        {
            // handle exception
        }
        string fileType = @"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        string fileName = "excel.xlsx";
    
        return File(excelFile, fileType, fileName);
    }
    

    Response
    将仅在web请求的上下文中填充,您如何调用代码?我将分为几个步骤。创建Excel的部分应该只返回一个表示文件内容的字节数组。它不应该关心文件的去向——流式传输到web客户端,保存到文件中,等等。您的网页调用该代码,获取字节数组,并将其流式传输到客户端。我有Angular6/MVC项目。我需要根据用户选择调用一些SQL,并在单独的选项卡中使用每个数据集的数据创建excel工作簿。您能给出一些建议吗?您可以使用api端点返回字节[]。你在用ApiConrollers吗?不,我有MVC控制器。不知道阿皮康罗。这有什么帮助?