C # SQL in Excel
Call you SP from the database
public DataTable GetDrugUtilizationReport_IndividualGenerateFile(long pharmacyId, DateTime from, DateTime to, long DrugNameId, int sortBy) { var parameters = new Dictionary<string, object> { { "PharmacyId", pharmacyId }, { "DateFrom", from }, { "DateTo", to }, { "DrugNameId", DrugNameId }, { "SortBy", sortBy } }; return ExecuteQuery("RPT_DrugUtilizationReportByIndividualGenerateFile", CommandType.StoredProcedure, parameters); }
Use in C # code
private void OnCreateFileCommand(object obj) { string path, parameterLabel; path = ConfigurationManager.AppSettings["VSSPORTEXELExportPath"]; parameterLabel = FromDate.ToString("yyyy-MM-dd") + "_" + ToDate.ToString("yyyy-MM-dd"); try { path = ExcelUtlity.ExportDataToExcel( dataTable: context.GetDrugUtilizationReport_IndividualGenerateFile(GlobalVar.Pharminfo.pharminfo_PK, FromDate, ToDate, SelectedDrug != null ? SelectedDrug.drugnameid_PK : 0, sortBy: SortBy + 1), directoryPath: path, fileName_withoutExt: "DrugUtilizationReport" + "__" + parameterLabel, skipComplexObjects: true, skipInheritedProps: true); DXMessageBox.Show("Data exported successfully at \"" + path + "\".", GlobalVar.MessageTitle, MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { string errorMessage = ExceptionHelper.ProcessException(ex); DXMessageBox.Show(errorMessage, GlobalVar.MessageTitle, MessageBoxButton.OK, MessageBoxImage.Error); } }
Excel Utility
public static string ExportDataToExcel(DataTable dataTable, string directoryPath, string fileName_withoutExt, bool skipComplexObjects, bool skipInheritedProps, string[] skipProps = null) { if (directoryPath[directoryPath.Length - 1] == '\\') // no need to check for >0 length. let it throw an exection for that directoryPath = directoryPath + "\\"; using (var spreadSheet = new SpreadsheetControl()) { // Create new excel document and import the datatable to the worksheet spreadSheet.CreateNewDocument(); spreadSheet.BeginUpdate(); var worksheet = spreadSheet.Document.Worksheets.ActiveWorksheet; worksheet.Import(source: dataTable, addHeader: true, firstRowIndex: 0, firstColumnIndex: 0); // applying style on header Range range = worksheet.Range["A1:" + worksheet.Columns[worksheet.Columns.LastUsedIndex].Heading+"1"]; Formatting rangeFormatting = range.BeginUpdateFormatting(); rangeFormatting.Fill.BackgroundColor = System.Drawing.Color.LightSteelBlue; rangeFormatting.Font.FontStyle = SpreadsheetFontStyle.Bold; range.AutoFitColumns(); range.EndUpdateFormatting(rangeFormatting); spreadSheet.EndUpdate(); fileName_withoutExt += ".xlsx"; Directory.CreateDirectory(directoryPath); // if directory already exists, CreateDirectory will do nothing spreadSheet.SaveDocument(directoryPath + fileName_withoutExt, DocumentFormat.OpenXml); return directoryPath + fileName_withoutExt; } }
Using Microsoft Office dll
public bool WriteDataTableToExcel(System.Data.DataTable dataTable, string worksheetName, string saveAsLocation, string ReporType) { Microsoft.Office.Interop.Excel.Application excel; Microsoft.Office.Interop.Excel.Workbook excelworkBook; Microsoft.Office.Interop.Excel.Worksheet excelSheet; Microsoft.Office.Interop.Excel.Range excelCellrange; try { // Start Excel and get Application object. excel = new Microsoft.Office.Interop.Excel.Application(); // for making Excel visible excel.Visible = false; excel.DisplayAlerts = false; // Creation a new Workbook excelworkBook = excel.Workbooks.Add(Type.Missing); // Workk sheet excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelworkBook.ActiveSheet; excelSheet.Name = worksheetName; excelSheet.Cells[1, 1] = ReporType; excelSheet.Cells[1, 2] = "Date : " + DateTime.Now.ToShortDateString(); // loop through each row and add values to our sheet int rowcount = 2; foreach (DataRow datarow in dataTable.Rows) { rowcount += 1; for (int i = 1; i <= dataTable.Columns.Count; i++) { // on the first iteration we add the column headers if (rowcount == 3) { excelSheet.Cells[2, i] = dataTable.Columns[i - 1].ColumnName; excelSheet.Cells.Font.Color = System.Drawing.Color.Black; } excelSheet.Cells[rowcount, i] = datarow[i - 1].ToString(); //for alternate rows if (rowcount > 3) { if (i == dataTable.Columns.Count) { if (rowcount % 2 == 0) { excelCellrange = excelSheet.Range[excelSheet.Cells[rowcount, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]]; FormattingExcelCells(excelCellrange, "#CCCCFF", System.Drawing.Color.Black, false); } } } } } // now we resize the columns excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]]; excelCellrange.EntireColumn.AutoFit(); Microsoft.Office.Interop.Excel.Borders border = excelCellrange.Borders; border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; border.Weight = 2d; excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[2, dataTable.Columns.Count]]; FormattingExcelCells(excelCellrange, "#000099", System.Drawing.Color.White, true); //now save the workbook and exit Excel excelworkBook.SaveAs(saveAsLocation); ; excelworkBook.Close(); excel.Quit(); return true; } catch (Exception ex) { DXMessageBox.Show(ex.Message); return false; } finally { excelSheet = null; excelCellrange = null; excelworkBook = null; } } /// <summary> /// FUNCTION FOR FORMATTING EXCEL CELLS /// </summary> /// <param name="range"></param> /// <param name="HTMLcolorCode"></param> /// <param name="fontColor"></param> /// <param name="IsFontbool"></param> public void FormattingExcelCells(Microsoft.Office.Interop.Excel.Range range, string HTMLcolorCode, System.Drawing.Color fontColor, bool IsFontbool) { range.Interior.Color = System.Drawing.ColorTranslator.FromHtml(HTMLcolorCode); range.Font.Color = System.Drawing.ColorTranslator.ToOle(fontColor); if (IsFontbool == true) { range.Font.Bold = IsFontbool; } }