See

Thursday, November 1, 2007

Excel Report in .Net 2.0 Using C#

This a program to gererate Excel report through .net using c#

Steps
1. u need to add areference to com component microsoft.Office.Excel dll
2. Store the result data from table to a data table loop it to generate the report.
add reference as using Excel;


using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.IO;
using System.Data.SqlClient;
using System.Data;
using Excel;

namespace Student
{
class Program
{
static void Main(string[] args)
{
Excel.Application oXL = new Excel.Application();
Excel.Workbook oBook;
Excel.Worksheet oSheet, oSheet1, oSheet2;
string fileNameMerchant = null;
SqlConnection sCon=null;
try
{
// Initialization of Database connections
sCon = new SqlConnection(@"Data Source=.\SqlExpress; Initial catalog=aspnetdb; integrated security =true");
sCon.Open();
oBook = oXL.Workbooks.Add(Type.Missing);
oXL.Visible = false;

if (oBook.Worksheets.Count > 0)
{
oSheet = (Excel.Worksheet)oBook.Sheets[1];
oSheet.Activate();
SqlDataAdapter da = new SqlDataAdapter("select *from student", sCon);
DataSet ds = new DataSet();
da.Fill(ds);
Range rg = oSheet.get_Range("A1", "B1");
rg.Select();

rg = oSheet.get_Range(“A1”, Type.Missing);
rg.Cells.ColumnWidth = 30;
rg.Font.Bold = true;
rg.Font.Name = "Arial";
rg.Font.Size = 10;
rg.Value2 = " Student Detail ";



int 3 = 1;
string s = "A" + x.ToString();
rg = oSheet.get_Range(s.ToString(), Type.Missing);
rg.Cells.ColumnWidth = 30;
rg.Font.Bold = true;
rg.Font.Name = "Arial";
rg.Font.Size = 10;
rg.Value2 = "First name";

s = "B" + x.ToString();
rg = oSheet.get_Range(s.ToString(), Type.Missing);
rg.Cells.ColumnWidth = 30;
rg.Font.Bold = true;
rg.Font.Name = "Arial";
rg.Font.Size = 10;
rg.Value2 = "Last name";
int i = 0;
x++;
int count = ds.Tables[0].Rows.Count;
while (i < count)
{

string ss = "A" + x.ToString();
rg = oSheet.get_Range(ss.ToString(), Type.Missing);
rg.Cells.ColumnWidth = 40;
rg.HorizontalAlignment = Excel.Constants.xlRight;
rg.Value2 = "'" + ds.Tables[0].Rows[i][0].ToString();

ss = "B" + x.ToString();
rg = oSheet.get_Range(ss.ToString(), Type.Missing);
rg.Cells.ColumnWidth = 40;
rg.HorizontalAlignment = Excel.Constants.xlRight;
rg.Value2 = ds.Tables[0].Rows[i][1];
x++;
i++;
}
}
fileNameMerchant = System.Environment.CurrentDirectory+"/"+"Studentdetail.xls";
oXL.ActiveWorkbook.SaveAs(fileNameMerchant, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

oXL.ActiveWorkbook.Close(true, fileNameMerchant, false);
Console.WriteLine("Excel Repor has ben generated successfully at " + fileNameMerchant);
Console.WriteLine("Press any key to close the application");
Console.Read();

}
catch (Exception ex)
{
Console.WriteLine(ex.Message);

}
finally
{
sCon.Close();
}
}
}

}

No comments: