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

How to write data into Excel file and save it? EPPlus C#

我有从 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);

}

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

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