private void TOExcel(DataTable ds) { //declaring the application Microsoft.Office.Interop.Excel.Application oAppln; //declaring work book Microsoft.Office.Interop.Excel.Workbook oWorkBook; //declaring worksheet Microsoft.Office.Interop.Excel.Worksheet oWorkSheet; //declaring the range Microsoft.Office.Interop.Excel.Range oRange;
try { oAppln = new Microsoft.Office.Interop.Excel.Application(); oWorkBook = (Microsoft.Office.Interop.Excel.Workbook)(oAppln.Workbooks.Add(true)); oWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWorkBook.ActiveSheet;
int iRow = 2;
//check for data if (ds.Rows.Count > 0) { //headers for (int j = 0; j < ds.Columns.Count; j++) { oWorkSheet.Cells[1, j + 1] = ds.Columns[j].ColumnName; } //inserting datas for (int rowNo = 0; rowNo < ds.Rows.Count; rowNo++) { //in each row for (int colNo = 0; colNo < ds.Columns.Count; colNo++) {
// in each column oWorkSheet.Cells[iRow, colNo + 1] = ds.Rows[rowNo][colNo].ToString(); } //moving to next row iRow++; } } //range of the excel sheet oRange = oWorkSheet.get_Range("A1", "IV1"); oRange.EntireColumn.AutoFit(); oAppln.UserControl = false; //path declaration string strFile = "c:/" + "report" + ".xls";
// to view Excel sheet... oAppln.Visible = true;
// to save the excel sheet.... oWorkBook.SaveAs( strFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, false, false, null, null , null); } catch (Exception theException) { MessageBox.Show(theException.Message.ToString()); } } |