Vs C # import database EXCLE,
Using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Data;
Using System. Data. SqlClient;
Using System. Drawing;
Using System. Text;
Using System. Windows. Forms;
Using Microsoft. Office. Core;
Using Excel = Microsoft. Office. Interop. Excel;
Namespace ExcelReport
{
Public partial class FormExcelNormal: Form
{
Public FormExcelNormal ()
{
InitializeComponent ();
}
Private void FormExcelNormal_Load (object sender, EventArgs e)
{
DataSet objDataSet = FormUtil. FormGridView ("MEMBERINFO ");
DgvMemberInfo. DataSource = objDataSet. Tables ["MEMBERINFO"];
}
// Export data in Excel
Private void btnExcelOut_Click (object sender, EventArgs e)
{
String strConnect = System. Configuration. ConfigurationSettings. receivettings ["connStr"];
SqlConnection objConnection = new SqlConnection (strConnect );
SqlCommand objCommand = new SqlCommand ("select membername, SEX, AREA, email from memberinfo", objConnection );
DataSet objDataset = new DataSet ();
SqlDataAdapter objAdapter = new SqlDataAdapter (objCommand );
// Data Filling
ObjConnection. Open ();
ObjAdapter. Fill (objDataset, "Excel ");
ObjConnection. Close ();
// Create an Excel Object
Excel. Application xlApp = new Excel. Application ();
Excel. Workbook wb = xlApp. Workbooks. Add (Excel. XlWBATemplate. xlWBATWorksheet );
Excel. Worksheet ws = (Excel. Worksheet) wb. Worksheets [1];
Excel. Range targetRange = xlApp. get_Range ("A1 ");
// Set the title
XlApp. Cells [1, 1] = "member name ";
XlApp. Cells [1, 2] = "gender ";
XlApp. Cells [1, 3] = "nationality ";
XlApp. Cells [1, 4] = "email ";
// Set the format
Int iMaxRow = objDataset. Tables ["Excel"]. Rows. Count;
Int iMaxCol = objDataset. Tables ["Excel"]. Columns. Count;
Ws. get_Range (ws. Cells [1, 1], ws. Cells [1, iMaxCol]). Font. Name = "";
Ws. get_Range (ws. Cells [1, 1], ws. Cells [1, iMaxCol]). Font. Bold = true;
Ws. get_Range (ws. Cells [1, 1], ws. Cells [iMaxRow + 1, iMaxCol]). Borders. LineStyle = 1;
// Fill in data
For (int iRow = 0; iRow <iMaxRow; iRow ++)
{
For (int iCol = 0; iCol <iMaxCol; iCol ++)
{
XlApp. Cells [iRow + 2, iCol + 1] = objDataset. Tables ["Excel"]. Rows [iRow] [iCol]. ToString ();
}
}
// Save the Excel file
XlApp. Save ("sheet1.xls ");
// Open Excel
XlApp. Visible = true;
}
}
}