Asp.net 如何将数据写入Excel文件并保存?EPPlus C#

Asp.net 如何将数据写入Excel文件并保存?EPPlus C#,asp.net,.net,excel,epplus,Asp.net,.net,Excel,Epplus,我有从SQl执行多个存储过程的代码。但是,我在如何将存储过程中的数据写入Excel文件方面遇到了一个问题。将数据写入excel文件后,我想保存excel工作簿。我怎样才能做到这一点?非常感谢您的帮助 这就是我到目前为止所做的: public static void ExecuteStoredProcedures() { using (SqlConnection connection = new SqlConnection("Data Source=the

我有从SQl执行多个存储过程的代码。但是,我在如何将存储过程中的数据写入Excel文件方面遇到了一个问题。将数据写入excel文件后,我想保存excel工作簿。我怎样才能做到这一点?非常感谢您的帮助

这就是我到目前为止所做的:

    public static void ExecuteStoredProcedures()
    {
            using (SqlConnection connection = new SqlConnection("Data Source=the connection goes here.."))
            {
                SqlTransaction transaction;

                connection.Open();
                transaction = connection.BeginTransaction();

                try
                {
                    SqlCommand cmdOne = new SqlCommand("exec ", connection);
                    SqlCommand cmdTwo = new SqlCommand("exec", connection);
                    SqlCommand cmdThree = new SqlCommand("exec", connection);

                    cmdOne.ExecuteNonQuery();
                    cmdTwo.ExecuteNonQuery();
                    cmdThree.ExecuteNonQuery();
                    transaction.Commit();              
                }

                catch (Exception ex)
                {
                    transaction.Rollback();
                    connection.Close();
                }
            }
        }

        public static void SaveExcelFile()
        {

            string SheetLocation = ConfigurationManager.AppSettings["SheetLocation"];

            if (!System.IO.Directory.Exists(SheetLocation))
            {
                System.IO.Directory.CreateDirectory(SheetLocation);
            }

            ExecuteStoredProcedures(); //Should I call the method to load the data that comes from the stored procedures? Or what should I do to write the data into the file?

            var newFile = new FileInfo(@"C:\Users\");

            using (ExcelPackage xlPackage = new ExcelPackage(newFile))
            {                         
                xlPackage.Save();
            }                     
        }

以数据集或数据表的形式从存储过程获取数据

创建工作表:

using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{                         
     ExcelWorksheet ws = xlPackage.Workbook.Worksheets.Add(AnyName);

}
像二维数组一样循环数据表的行和列,在工作表中创建单元格,并在创建的单元格中添加数据:

int rowIndex = 0
foreach (DataRow DataTableRow in dt.Rows)
{
    int colIndex = 1;
    rowIndex++;
    foreach (DataColumn DataTableColumn in dt.Columns)
    {
         var cell = ws.Cells[rowIndex, colIndex];
         cell.Value = DataTableRow[DataTableColumn.ColumnName];
         colIndex++;
    }
}

你看了文件了吗?看起来你什么都没试过。请阅读文档和示例。他们已经展示了该做什么。EPPlus有一个LoadCollection和一个LoadDataTable,可以在一次调用中将任何数据加载到Excel范围中。为什么不使用内置方法加载DataTable?