Tuesday, November 10, 2009

Create and Format an Excel in Asp.net

A simple code snippet to create excel and write some date to cell from C#.
Step 1: Add reference to " microsoft excel 12.0 object library " in the project.
Step 2: Include the namespace " using Excel = Microsoft.Office.Interop.Excel; "
Step 3: In the click event of export button:
string strCurrentDir = Server.MapPath(".") + "\\";
Excel.Application excel = new Excel.ApplicationClass();
excel.Visible = false;
Excel._Workbook workbook = excel.Workbooks.Add(Missing.Value);
Excel.Sheets sheets = workbook.Worksheets;
Excel._Worksheet exlSheet = (Excel.Worksheet)sheets.get_Item("Sheet1");
summarySheet.Name = "Report Name";
Excel.Range headerRng = (Excel.Range)exlSheet .get_Range("A1", "B1");
headerRng.MergeCells = true; headerRng.Value2 = "Report Header";
headerRng.Font.Bold = true;
headerRng.Font.Name = "Arial";
headerRng.Font.Size = 18;
headerRng.WrapText = true;
headerRng.HorizontalAlignment = Excel.Constants.xlCenter;
headerRng.Interior.Color = System.Drawing.Color.Gray.ToArgb();
headerRng.Borders.Weight = 3;
headerRng.Borders.LineStyle = Excel.Constants.xlSolid;
headerRng.Cells.RowHeight = 30;
headerRng.EntireColumn.AutoFit();

workbook.SaveAs(strCurrentDir + "ExportReport.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, false, false, null, null, null);

No comments:

Computers Add to Technorati Favorites Programming Blogs - BlogCatalog Blog Directory