public void ExportToExcel(DataTable Tbl, string ExcelFilePath) { try { if (Tbl == null || Tbl.Columns.Count == 0) { throw new Exception("ExportToExcel: Null or empty input table!\n"); } // load excel, and create a new workbook Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application(); excelApp.Workbooks.Add(); // single worksheet Microsoft.Office.Interop.Excel._Worksheet workSheet = excelApp.ActiveSheet; // column headings for (int i = 0; i < Tbl.Columns.Count; i++) { workSheet.Cells[1, (i + 1)] = Tbl.Columns[i].ColumnName; } // rows for (int i = 0; i < Tbl.Rows.Count; i++) { // to do: format datetime values before printing for (int j = 0; j < Tbl.Columns.Count; j++) { workSheet.Cells[(i + 2), (j + 1)] = Tbl.Rows[i][j]; } } // check fielpath if (ExcelFilePath != null && ExcelFilePath != "") { try { workSheet.SaveAs(ExcelFilePath); excelApp.Quit(); //MessageBox.Show("Excel file saved!"); } catch (Exception ex) { throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n" + ex.Message); } } else // no filepath is given { excelApp.Visible = true; } } catch (Exception ex) { throw new Exception("ExportToExcel: \n" + ex.Message); } }
private void отчетToolStripMenuItem_Click(object sender, EventArgs e) { SelectDateRange srd = new SelectDateRange(); srd.dateTimePicker1.Value = (DateTime)db.Invoices.First().sale_date; DialogResult dr = srd.ShowDialog(this); DateTime startDate = srd.dateTimePicker1.Value; DateTime endDate = srd.dateTimePicker2.Value; List <Invoice> invoices = db.Invoices.Where(i => i.sale_date.Value >= startDate && i.sale_date.Value <= endDate).OrderByDescending(i => i.Product.name).ToList(); //string[] head = { "Код", "Название товара", "Цена за единицу", "Заказано КГ.", "Дата продажи", "Общая стоимость" }; if ((dr == DialogResult.OK) && (0 < invoices.Count)) { // Load Excel application Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); // Create empty workbook excel.Workbooks.Add(); // Create Worksheet from active sheet Microsoft.Office.Interop.Excel._Worksheet workSheet = excel.ActiveSheet; try { workSheet.Cells[1, "A"] = "Код накладной"; workSheet.Cells[1, "B"] = "Название товара"; workSheet.Cells[1, "C"] = "Цена за единицу"; workSheet.Cells[1, "D"] = "Заказано (КГ.)"; workSheet.Cells[1, "E"] = "Дата покупки"; workSheet.Cells[1, "F"] = "Сумма за покупку"; workSheet.Cells[1, "H"] = "Название товара"; workSheet.Cells[1, "I"] = "Количество заказанного товара"; workSheet.Cells[1, "K"] = "Нужно закупить больше:"; workSheet.Cells[1, "L"] = "Нужно закупить меньше:"; int row = 2; ArrayList nameArray = new ArrayList(); ArrayList sumArray = new ArrayList(); int sum; string name; foreach (Invoice invoice in invoices) { workSheet.Cells[row, "A"] = invoice.invoice_code; workSheet.Cells[row, "B"] = invoice.Product.name; workSheet.Cells[row, "C"] = string.Format("{0} грн.", invoice.Product.price); workSheet.Cells[row, "D"] = string.Format("{0} кг.", invoice.quantity); workSheet.Cells[row, "E"] = invoice.sale_date.Value.Date; workSheet.Cells[row, "F"] = string.Format("{0} грн.", invoice.price); name = db.Invoices.Where(nn => nn.product_id == invoice.Product.id && nn.sale_date.Value >= startDate && nn.sale_date.Value <= endDate).First().Product.name.ToString(); sum = (int)db.Invoices.Where(i => i.Product.name == invoice.Product.name && i.sale_date.Value >= startDate && i.sale_date.Value <= endDate).Sum(s => s.quantity); if (!nameArray.Contains(name)) { nameArray.Add(name); } if (!sumArray.Contains(sum)) { sumArray.Add(sum); } row++; } row = 2; foreach (string nameRow in nameArray) { workSheet.Cells[row, "H"] = nameRow; row++; } row = 2; foreach (int sumRow in sumArray) { workSheet.Cells[row, "I"] = sumRow; row++; } Excel.ChartObjects chartObjs = (Excel.ChartObjects)workSheet.ChartObjects(Type.Missing); Excel.ChartObject chartObj = chartObjs.Add(100, 20, 150, 200); Excel.Chart xlChart = chartObj.Chart; Excel.Range rg = workSheet.get_Range("H2:H" + (row - 1).ToString(), "I2:I" + (row - 1).ToString()); xlChart.ChartType = Excel.XlChartType.xlPieExploded; xlChart.SetSourceData(rg, Type.Missing); //rg.FormulaLocal = "MAX(I2:I"+(row-1).ToString(); //workSheet.Cells[2, "M"].Value = "=MAX(I2:I" + (row - 1).ToString(); //workSheet.Cells[2, "N"].Value = "=MIN(I2:I" + (row - 1).ToString(); //for (int i = 2; i < row; i++) // { // workSheet.Cells[i, "K"].Value = "=ЕСЛИ(M2=I" + i.ToString() + ";H" + i.ToString() + ";0)"; // } //for (int i = 2; i < row; i++) // { // workSheet.Cells[i, "L"].Value = "=ЕСЛИ(N2=I" + i.ToString() + ";H" + i.ToString() + ";0)"; // } // rg.FormulaLocal = "MAX(I2:I"+(row-1).ToString(); //rg.FormulaLocal = "MIN(I2:I"+(row-1).ToString(); // Apply some predefined styles for data to look nicely :) workSheet.Range["A1"].AutoFormat(Microsoft.Office.Interop.Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic1); workSheet.Range["H1"].AutoFormat(Microsoft.Office.Interop.Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic1); workSheet.Range["K1"].AutoFormat(Microsoft.Office.Interop.Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic1); // Define filename string fileName = string.Format(@"{0}\ExcelData.xlsx", Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)); // Save this data as a file workSheet.SaveAs(fileName); // Display SUCCESS message MessageBox.Show(string.Format("Файл '{0}' успешно сохранен!", fileName)); } catch (Exception exception) { MessageBox.Show("Exception", "Ошибка записи файла!\n" + exception.Message, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { // Quit Excel application excel.Quit(); //excel.Workbooks.Open(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)); // Release COM objects (very important!) if (excel != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); } if (workSheet != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet); } // Empty variables excel = null; workSheet = null; // Force garbage collector cleaning GC.Collect(); } } else { MessageBox.Show("В выбраном диапазоне, нет накладных!"); } if (dr == DialogResult.Cancel) { return; } }
/// <summary> /// Export DataTable to Excel file /// </summary> /// <param name="DataTable">Source DataTable</param> /// <param name="ExcelFilePath">Path to result file name</param> public static void ExportToExcel(this System.Data.DataTable DataTable, string ExcelFilePath = null) { try { int ColumnsCount; if (DataTable == null || (ColumnsCount = DataTable.Columns.Count) == 0) { throw new Exception("ExportToExcel: Null or empty input table!\n"); } // load excel, and create a new workbook Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application(); Excel.Workbooks.Add(); // single worksheet Microsoft.Office.Interop.Excel._Worksheet Worksheet = Excel.ActiveSheet; object[] Header = new object[ColumnsCount]; // column headings for (int i = 0; i < ColumnsCount; i++) { Header[i] = DataTable.Columns[i].ColumnName; } Microsoft.Office.Interop.Excel.Range HeaderRange = Worksheet.get_Range((Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[1, 1]), (Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[1, ColumnsCount])); HeaderRange.Value = Header; HeaderRange.Font.Bold = true; // DataCells int RowsCount = DataTable.Rows.Count; object[,] Cells = new object[RowsCount, ColumnsCount]; for (int j = 0; j < RowsCount; j++) { for (int i = 0; i < ColumnsCount; i++) { Cells[j, i] = DataTable.Rows[j][i]; } } Worksheet.get_Range((Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[2, 1]), (Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[RowsCount + 1, ColumnsCount])).Value = Cells; // check fielpath if (ExcelFilePath != null && ExcelFilePath != "") { try { Worksheet.SaveAs(ExcelFilePath); Excel.Quit(); } catch (Exception ex) { throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n" + ex.Message); } } else // no filepath is given { Excel.Visible = true; } } catch (Exception ex) { throw new Exception("ExportToExcel: \n" + ex.Message); } }
private void CreateExcel(List <Account> accounts) { excelApp.Visible = false; excelApp.Workbooks.Add(Type.Missing); Microsoft.Office.Interop.Excel._Worksheet worksheet = excelApp.ActiveSheet; worksheet.Cells[1, "A"] = "Bank"; worksheet.Cells[1, "B"] = "Req Id"; worksheet.Cells[1, "C"] = "Account No"; worksheet.Cells[1, "D"] = "Name"; worksheet.Cells[1, "E"] = "Leaves Qty"; worksheet.Cells[1, "F"] = "Delevery Branch"; worksheet.Cells[1, "G"] = "Currency"; worksheet.Cells[1, "H"] = "St No"; worksheet.Cells[1, "I"] = "End No"; worksheet.Cells[1, "J"] = "Routing"; worksheet.Cells[1, "K"] = "MICR A/c"; worksheet.Cells[1, "L"] = "TC"; worksheet.Cells[1, "M"] = "Image"; int row = 1; foreach (Account account in accounts) { row++; worksheet.Cells[row, "A"] = account.Bank; worksheet.Cells[row, "B"].NumberFormat = "@"; worksheet.Cells[row, "B"].Value = account.ReqId; worksheet.Cells[row, "C"].NumberFormat = "@"; worksheet.Cells[row, "C"] = account.AccountNo; worksheet.Cells[row, "D"] = account.Name; worksheet.Cells[row, "E"] = 1.ToString(); worksheet.Cells[row, "F"] = account.Branch; worksheet.Cells[row, "G"] = account.Currency; worksheet.Cells[row, "H"].NumberFormat = "@"; worksheet.Cells[row, "H"] = account.StartStNo; worksheet.Cells[row, "I"].NumberFormat = "@"; worksheet.Cells[row, "I"] = account.EndStNo; worksheet.Cells[row, "J"].NumberFormat = "@"; worksheet.Cells[row, "J"] = account.Routing; worksheet.Cells[row, "K"].NumberFormat = "@"; worksheet.Cells[row, "K"] = account.MICRAc; worksheet.Cells[row, "L"].NumberFormat = "@"; worksheet.Cells[row, "L"] = account.Type; //worksheet.Cells[row, "M"] = account.Image; //worksheet.Cells[row, "M"].Shapes.AddPicture(@"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum - Copy.jpg",Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 49, 49, 49,49); // var commnetImage = worksheet.Shapes.AddPicture(@"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum - Copy.jpg", Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse, // 0, 0, 100, 200); Excel.Range oRange = (Excel.Range)worksheet.Cells[row, "M"]; oRange.set_Item(1, 1, account.Image); worksheet.Paste(oRange, account.Image); } //worksheet.Range["A1"].AutoFormat(Microsoft.Office.Interop.Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic1); if (File.Exists(@"D:Data\BankAsia.xlsx")) { File.Delete(@"D:Data\BankAsia.xlsx"); } worksheet.SaveAs(@"D:Data\BankAsia.xlsx"); excelApp.Quit(); }
private void btn_raport_Click(object sender, EventArgs e) { DateTime day = DateTime.Today; DateTime d = day.AddDays(-30); string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); path += "\\RaportVanzari.xlsx"; if (File.Exists(path)) { File.Delete(path); } // Load Excel application Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); // Create empty workbook excel.Workbooks.Add(); // Create Worksheet from active sheet Microsoft.Office.Interop.Excel._Worksheet workSheet = excel.ActiveSheet; // I created Application and Worksheet objects before try/catch, // so that i can close them in finnaly block. // It's IMPORTANT to release these COM objects!! try { // ------------------------------------------------ // Creation of header cells // ------------------------------------------------ workSheet.Cells[1, "A"] = "VIN"; workSheet.Cells[1, "B"] = "Clinet"; workSheet.Cells[1, "C"] = "Vanzator"; workSheet.Cells[1, "D"] = "Pret Vanzare"; workSheet.Cells[1, "E"] = "Data"; var context = new Parc_AutoDataContext(); var result = from s in context.Vanzaris.Take(30) where (s.Data >= d) select new { VIN = s.VIN, Client = s.Client, Vanzator = s.Vanzator, Pret_Vanzare = s.Pret_vanzare, Data = s.Data }; int row = 2; // start row (in row 1 are header cells) foreach (var car in result) { workSheet.Cells[row, "A"] = car.VIN; workSheet.Cells[row, "B"] = car.Client; workSheet.Cells[row, "C"] = car.Vanzator; workSheet.Cells[row, "D"] = car.Pret_Vanzare; workSheet.Cells[row, "E"] = car.Data; row++; } // Apply some predefined styles for data to look nicely :) //workSheet.Range["A1"].AutoFormat(Microsoft.Office.Interop.Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic1);// // Save this data as a file workSheet.SaveAs(path); // Display SUCCESS message MessageBox.Show(string.Format("The file '{0}' is saved successfully!", path)); } catch (Exception exception) { MessageBox.Show("Exception", "There was a PROBLEM saving Excel file!\n" + exception.Message, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
//public static string ToString<T>(this IList<T> list, string include = "", string exclude = "") //{ // //Variables for build string // string propStr = string.Empty; // StringBuilder sb = new StringBuilder(); // //Get property collection and set selected property list // PropertyInfo[] props = typeof(T).GetProperties(); // List<GetAbsentMembersByID_Result> Absentemployee = MembersAttendanceHistoryController.GetAbsentMemberById(txtSearchText.Text, SortField, SortDir, txtFromDate.Text, txtToDate.Text, memberId); // //Add list name and total count // string typeName = GetSimpleTypeName(list); // sb.AppendLine(string.Format("{0} List - Total Count: {1}", typeName, list.Count.ToString())); // //Iterate through data list collection // foreach (var item in list) // { // sb.AppendLine(""); // //Iterate through property collection // foreach (var prop in Absentemployee) // { // //Construct property name and value string // propStr = prop.MemberName + ": " + prop.MemberName; // sb.AppendLine(propStr); // } // } // return sb.ToString(); //} //private static string GetSimpleTypeName<T>(IList<T> list) //{ // string typeName = list.GetType().ToString(); // int pos = typeName.IndexOf("[") + 1; // typeName = typeName.Substring(pos, typeName.LastIndexOf("]") - pos); // typeName = typeName.Substring(typeName.LastIndexOf(".") + 1); // return typeName; //} //private static List<PropertyInfo> GetSelectedProperties(PropertyInfo[] props, string include, string exclude) //{ // List<PropertyInfo> propList = new List<PropertyInfo>(); // if (include != "") //Do include first // { // var includeProps = include.ToLower().Split(',').ToList(); // foreach (var item in props) // { // var propName = includeProps.Where(a => a == item.Name.ToLower()).FirstOrDefault(); // if (!string.IsNullOrEmpty(propName)) // propList.Add(item); // } // } // else if (exclude != "") //Then do exclude // { // var excludeProps = exclude.ToLower().Split(','); // foreach (var item in props) // { // var propName = excludeProps.Where(a => a == item.Name.ToLower()).FirstOrDefault(); // if (string.IsNullOrEmpty(propName)) // propList.Add(item); // } // } // else //Default // { // propList.AddRange(props.ToList()); // } // return propList; //} //public static void ToExcel<T>(this IList<T> list, string include = "", string exclude = "") //{ // //Get property collection and set selected property list // PropertyInfo[] props = typeof(T).GetProperties(); // List<PropertyInfo> propList = GetSelectedProperties(props, include, exclude); // //Get simple type name // string typeName = GetSimpleTypeName(list); // //Convert list to array for selected properties // object[,] listArray = new object[list.Count + 1, propList.Count]; // //Add property name to array as the first row // int colIdx = 0; // foreach (var prop in propList) // { // listArray[0, colIdx] = prop.Name; // colIdx++; // } // //Iterate through data list collection for rows // int rowIdx = 1; // foreach (var item in list) // { // colIdx = 0; // //Iterate through property collection for columns // foreach (var prop in propList) // { // //Do property value // listArray[rowIdx, colIdx] = prop.GetValue(item, null); // colIdx++; // } // rowIdx++; // } // //Processing for Excel // object oOpt = System.Reflection.Missing.Value; // Excel.Application oXL = new Excel.Application(); // Excel.Workbooks oWBs = oXL.Workbooks; // Excel.Workbook oWB = oWBs.Add(Excel.XlWBATemplate.xlWBATWorksheet); // Excel.Worksheet oSheet = (Excel.Worksheet)oWB.ActiveSheet; // oSheet.Name = typeName; // Excel.Range oRng = oSheet.get_Range("A1", oOpt).get_Resize(list.Count + 1, propList.Count); // oRng.set_Value(oOpt, listArray); // //Open Excel // oXL.Visible = true; //} public void ExportToExcel(List <GetAbsentMembersByID_Result> cars) { // Load Excel application Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); // Create empty workbook excel.Workbooks.Add(); // Create Worksheet from active sheet Microsoft.Office.Interop.Excel._Worksheet workSheet = excel.ActiveSheet; // I created Application and Worksheet objects before try/catch, // so that i can close them in finnaly block. // It's IMPORTANT to release these COM objects!! try { // ------------------------------------------------ // Creation of header cells // ------------------------------------------------ workSheet.Cells[1, "A"] = "MemberName"; workSheet.Cells[1, "B"] = "MobileNumber"; workSheet.Cells[1, "C"] = "Member Id"; // ------------------------------------------------ // Populate sheet with some real data from "cars" list // ------------------------------------------------ int row = 2; // start row (in row 1 are header cells) foreach (GetAbsentMembersByID_Result car in cars) { workSheet.Cells[row, "A"] = car.MemberName; workSheet.Cells[row, "B"] = car.mobileNumber; workSheet.Cells[row, "C"] = car.membershipUniqueId; row++; } // Apply some predefined styles for data to look nicely :) workSheet.Range["A1"].AutoFormat(Microsoft.Office.Interop.Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic1); // Define filename DateTime date; date = DateTime.Now; string fileName = string.Format(@"{0}\EmpAbsent " + memberId + ".xlsx", Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)); // Save this data as a file workSheet.SaveAs(fileName); // Display SUCCESS message //MessageBox.Show(string.Format("The file '{0}' is saved successfully!", fileName)); } catch (Exception exception) { throw exception; //MessageBox.Show("Exception", //"There was a PROBLEM saving Excel file!\n" + exception.Message, //MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { // Quit Excel application excel.Quit(); // Release COM objects (very important!) if (excel != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); } if (workSheet != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet); } // Empty variables excel = null; workSheet = null; // Force garbage collector cleaning GC.Collect(); } }
public void ExportToExcel(List <FaturaOrnegi> faturas) { // Load Excel application Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); //excel.Visible = false; Microsoft.Office.Interop.Excel.Range excelCell; excel.DisplayAlerts = false; // Create empty workbook excel.Workbooks.Add(); // Create Worksheet from active sheet Microsoft.Office.Interop.Excel._Worksheet workSheet = excel.ActiveSheet; // I created Application and Worksheet objects before try/catch, // so that i can close them in finnaly block. // It's IMPORTANT to release these COM objects!! try { // ------------------------------------------------ // Creation of header cells // ------------------------------------------------ workSheet.Cells[1, "A"] = "Hesap no"; workSheet.Cells[1, "B"] = "Dönem"; workSheet.Cells[1, "C"] = "Kurulu Güç"; workSheet.Cells[1, "D"] = "Sözleşme Gücü"; workSheet.Cells[1, "E"] = "Enerji Bedeli Tüketim"; workSheet.Cells[1, "F"] = "Enerji Bedeli Birim Fiyat"; workSheet.Cells[1, "G"] = "Enerji Bedeli Tutar"; workSheet.Cells[1, "H"] = "Endüktif Tüketim"; workSheet.Cells[1, "I"] = "Endüktif Birim Fiyat"; workSheet.Cells[1, "J"] = "Endüktif Tutar"; workSheet.Cells[1, "K"] = "Kapasitif Tüketim"; workSheet.Cells[1, "L"] = "Kapasitif Birim Fiyat"; workSheet.Cells[1, "M"] = "Kapasitif Tutar"; workSheet.Cells[1, "N"] = "Vergi No"; workSheet.Cells[1, "O"] = "Müşteri Grubu"; workSheet.Cells[1, "P"] = "Dosya Adı"; // ------------------------------------------------ // Populate sheet with some real data from "Faturalar" list // ------------------------------------------------ int row = 2; // start row (in row 1 are header cells) foreach (FaturaOrnegi fatura in faturas) { workSheet.Cells[row, "A"] = fatura.hesapNo; workSheet.Cells[row, "B"] = fatura.donem; workSheet.Cells[row, "C"] = fatura.kuruluGuc; workSheet.Cells[row, "D"] = fatura.sozlesmeGucu; workSheet.Cells[row, "E"] = fatura.enerjiBedeliTuketim; workSheet.Cells[row, "F"] = fatura.enerjiBedeliBirim; workSheet.Cells[row, "G"] = fatura.enerjiBedeli; workSheet.Cells[row, "H"] = fatura.enduktifTuketim; workSheet.Cells[row, "I"] = fatura.enduktifBirim; workSheet.Cells[row, "J"] = fatura.enduktif; workSheet.Cells[row, "K"] = fatura.kapasitifTuketim; workSheet.Cells[row, "L"] = fatura.kapasitifBirim; workSheet.Cells[row, "M"] = fatura.kapasitif; workSheet.Cells[row, "N"] = fatura.vergiNo; workSheet.Cells[row, "O"] = fatura.musteriGrubu; excelCell = (Microsoft.Office.Interop.Excel.Range)workSheet.get_Range(("P" + row), ("P" + row)); workSheet.Hyperlinks.Add(excelCell, fatura.faturaYolu, Type.Missing, Type.Missing, fatura.faturaYolu.Substring(1 + fatura.faturaYolu.LastIndexOf(@"\"))); row++; } // Apply some predefined styles for data to look nicely :) workSheet.Range["A1"].AutoFormat(Microsoft.Office.Interop.Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic1); // Save this data as a file workSheet.SaveAs(excelPath); // Display SUCCESS message MessageBox.Show(string.Format("The file '{0}' is saved successfully!", excelPath)); } catch (Exception exception) { MessageBox.Show("Exception", "There was a PROBLEM saving Excel file!\n" + exception.Message, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { // Quit Excel application excel.Quit(); // Release COM objects (very important!) if (excel != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); } if (workSheet != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet); } // Empty variables excel = null; workSheet = null; // Force garbage collector cleaning GC.Collect(); } }