1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| private void button2_Click(object sender, System.EventArgs e)
{
//Export without SaveFileDialog
#region needs using RKLib.ExportData;
//// lblMessage.Visible = true;
//// lblMessage.Text = "";
// // Export all the details
// try
// {
// // Get the datatable to export
// DataTable dt = dsSelectionListeDiffere.Tables[0].Copy();
// dsSelectionListeDiffere = FrmFonctionPrincipale.getListeDifferesParClient(1);
// // Export all the details to Excel
//
//
// RKLib.ExportData.Export objExport = new RKLib.ExportData.Export("Win");
// objExport.ExportDetails(dt, Export.ExportFormat.Excel, "C:\\EmployeesInfo.xls");
// MessageBox.Show("Exporté Avec Succès dans C:\\EmployeesInfo.xls");
// }
// catch(Exception Ex)
// {
// MessageBox.Show(Ex.Message);
//// lblMessage.Text = Ex.Message;
// }
#endregion
//Export with SaveFileDialog
#region needs using Excel = Microsoft.Office.Interop.Excel; AND releaseObject Method
try
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel files (*.xls)|*.xls|All files (*.*)|*.*" ;
sfd.FilterIndex = 1 ;
sfd.RestoreDirectory = true ;
sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
if(sfd.ShowDialog() == DialogResult.OK)
{
if(sfd.FileName.Length > 0)
{
string data = null;
int i = 0;
int j = 0;
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (i = 0; i <= dsSelectionListeDiffere.Tables[0].Rows.Count - 1; i++)
{
for (j = 0; j <= dsSelectionListeDiffere.Tables[0].Columns.Count - 1; j++)
{
data = dsSelectionListeDiffere.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 1, j + 1] = data;
}
}
// Pass the full path to the SaveAs method
// string fullPathName = Path.Combine(folderName, "csharp.xls");
xlWorkBook.SaveAs(sfd.FileNames, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
}
}
catch(Exception ex )
{
MessageBox.Show(ex.Message);
}
#endregion
}
#region releaseObject Method
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
#endregion |
Partager