This article will help you on finding all the sheet name of
an excel worksheet in windows application using c#.net. In this we will browse
and the read all the present in the excel worksheet.
So for this article first we will create a new excel
worksheet and add some sheet in it.
Now create a new windows application and add a form in it.
Now add the below code in your form. Just call the add the browse the code on
button click.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Common;
namespace DemoWindowsApplication
{
public partial class ExcelSheetName : Form
{
public
ExcelSheetName()
{
InitializeComponent();
}
/// <summary>
/// Retrive Excel Worksheet Sheet Name and Display in
ListBox Using C#.Net Windows Application
/// </summary>
/// <param
name="sender"></param>
/// <param
name="e"></param>
private
void button1_Click(object
sender, EventArgs e)
{
OpenFileDialog
_objdlg = new OpenFileDialog();
DialogResult
_objdlgresult = _objdlg.ShowDialog();
if
(_objdlgresult == DialogResult.OK)
{
textBox1.Text =
_objdlg.FileName;
}
GetExcelSheetNames(textBox1.Text);
}
/// <summary>
///This method is for reading the sheet
///and loading the sheet name in listbox
/// </summary>
/// <param
name="path"></param>
/// <returns></returns>
public
void GetExcelSheetNames(string path)
{
List<string> sheets = new
List<string>();
string
connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data
Source={0};Extended Properties=""Excel
8.0;HDR=YES;IMEX=1;""", path);
DbProviderFactory
factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DbConnection
connection = factory.CreateConnection();
connection.ConnectionString =
connectionString;
connection.Open();
DataTable
tbl = connection.GetSchema("Tables");
connection.Close();
foreach
(DataRow row in
tbl.Rows)
{
string
sheetName = (string)row["TABLE_NAME"];
if
(sheetName.EndsWith("$"))
{
sheetName =
sheetName.Substring(0, sheetName.Length - 1);
}
sheets.Add(sheetName);
}
/*Bind data to listbox*/
listBox1.DataSource = sheets;
}
}
}
|
Now I will explain the above code. In above code I have used
openfiledialog for selecting the excel sheet. Now we have passed the file path
to the function for reading the excel sheet. In above code I have made the
collection of the sheet present in the excel worksheet. Now run the application
for output. After running the click on browse button to read the file.
DOWNLOAD
0 comments:
Please let me know your view