2017-09-27 71 views
-1

我有從SQl執行多個存儲過程的代碼。但是,我在如何將數據從存儲過程寫入Excel文件時遇到問題。將數據寫入Excel文件後,我想保存Excel工作簿。我怎樣才能做到這一點?很感謝任何形式的幫助。如何將數據寫入Excel文件並保存? EPPlus C#

這是我到目前爲止有:

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

你有沒有看文檔在所有?好像你還沒有嘗試過任何東西。 – mason

+0

閱讀文檔和示例。他們*已經*顯示要做什麼。 EPPlus具有LoadCollection *和* LoadDataTable,可以在單個調用中將任何數據加載到Excel範圍中。 –

回答

0

獲得來自數據集或數據表的形式存儲過程數據。 DataTable中的行和列像一個二維數組

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

爲什麼不使用內置方法加載DataTable? – mason