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

时间:2017-09-27 15:58:52

标签: asp.net .net excel epplus

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

1 个答案:

答案 0 :(得分:0)

以数据集或DataTables的形式从存储过程中获取数据。

创建工作表:

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

}

在数据表行和列中循环,如2d数组,并在工作表中创建单元格并在创建的单元格中添加数据:

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