Bind data from excel sheet to repeater or GridView - c#

What is efficient & simplest way to bind data from excel sheet to repeater or GridView.

I think it is easy to create OleDbDataAdapter and creating a DataSet will do the job.
You can easily bind a DataSet to gridview
eg
var conn = ("Provider=Microsoft.Jet.OLEDB.4.0;" +
("Data Source=add file path here;" +
"Extended Properties=\"Excel 8.0;\""));
var query = "SELECT table from [sheet1$]";
var adpterObj = new OleDbDataAdapter(SSQL, conn);
var ds = new DataSet();
adpterObj.Fill(ds);
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();

You should read data from Excel using any one library (OLEDB Connection, COM Object or any other) and after Puts result to any .Net objects (DataSet, DataTable) according to your requirement. then bind DataSet to your Repeater.

maybe this link will solve your problem
click me
public static DataSet ImportExcelXLS(string FileName, bool hasHeaders) {
string HDR = hasHeaders ? "Yes" : "No";
string strConn;
if (FileName.Substring(FileName.LastIndexOf('.')).ToLower() == ".xlsx")
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
else
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";
DataSet output = new DataSet();
using (OleDbConnection conn = new OleDbConnection(strConn)) {
conn.Open();
DataTable schemaTable = conn.GetOleDbSchemaTable(
OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
foreach (DataRow schemaRow in schemaTable.Rows) {
string sheet = schemaRow["TABLE_NAME"].ToString();
if (!sheet.EndsWith("_")) {
try {
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conn);
cmd.CommandType = CommandType.Text;
DataTable outputTable = new DataTable(sheet);
output.Tables.Add(outputTable);
new OleDbDataAdapter(cmd).Fill(outputTable);
} catch (Exception ex) {
throw new Exception(ex.Message + string.Format("Sheet:{0}.File:F{1}", sheet, FileName), ex);
}
}
}
}
return output;
}

First we have to browse
void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = "Excel files (*.xls)|*.xls";
fileDialog.InitialDirectory = "C:";
fileDialog.Title = "Select a Excel file";
if (fileDialog.ShowDialog() == DialogResult.OK)
txtMsg.Text = fileDialog.FileName;
if (string.IsNullOrEmpty(txtMsg.Text))
return;
}
Note: txtMsg.Text = fileDialog.FileName; //here file name keeping in one text box
Then we can upload excel sheet to gridview...
private void btnUpload_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtMsg.Text))
{
InsertBuyBackExceldata(txtMsg.Text);
}
}
Here we can call InsertBuyBackExceldata method
void InsertBuyBackExceldata(string filePath)
{
if (buyBackServiceProxyController == null)
buyBackServiceProxyController = new ProxyController();
buyBackServiceServiceProxy = buyBackServiceProxyController.GetProxy();
ListBuyBackrequest = new List();
String[] a= GetExcelSheetNames(filePath); // This method for get sheet names
var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", filePath);
//string a=filePath.
String sheetName = a[0];
var adapter = new OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, sheetName );
DataTable data = ds.Tables[sheetName ];
BindGrid(data);
}
here I am calling a method to get Sheet name.
private String[] GetExcelSheetNames(string excelFile)
{
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
return excelSheets;
}
catch (Exception ex)
{
return null;
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
//Excel Uploading to Gridview
void BindGrid(DataTable Data)
{
try
{
// Adding one check box
DataGridViewCheckBoxColumn chkSelection = new DataGridViewCheckBoxColumn();
chkSelection.Name = "Selection";
dgItemsForBuyBackGrid.Columns.Add(chkSelection);
int intCount = Data.Rows.Count;
if (i==true)
{
if (intCount > 0)
{
ExcelGrid.DataSource = Data;
ExcelGrid.BindPage();
}
else
{
ExcelGrid.DataSource = null;
ExcelGrid.BindPage();
return;
}
// Here I am setting Grid colomns properties this name should equal to Excel //column names.
ExcelGrid.Columns["BI"].ReadOnly = true;
ExcelGrid.Columns["AAA"].ReadOnly = true;
ExcelGrid.Columns["AAB"].ReadOnly = true;
ExcelGrid.Columns["AAC"].ReadOnly = true;
ExcelGrid.Columns["AAD"].ReadOnly = true;
ExcelGrid.Columns["AAE"].ReadOnly = true;
ExcelGrid.Columns["AAF"].ReadOnly = true;
ExcelGrid.Columns["AAG"].ReadOnly = false;
}
else
{
// Some Code
}
}
catch (Exception ex)
{
}
}
}
}
Excel 2007 and other versions Uploading to Gridview in .Net.
Steps:
1) AccessDatabaseEngine.exe --> (Install)
And some code changes from above code.
2) Browse Click
private void btnBrowse_Click(object sender, EventArgs e)
{
-------
fileDialog.Filter ="Excel files (*.xls;*xlsx;*xlsb)|*.xls;*xlsx;*xlsb";
// Show those extentional files.
--------------
}
3) Process Click
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0;";
Thank You :)

Related

C# Method to Load Excel File to DataTable or DateSet

good afternoon,
I am trying to create a method that returns the data of an excel file to call it through a FileDialog for example ... Here is my code:
public static DataSet MtdGetExcel(string prtlocalFile)
{
string sDBstrExcel = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=0\"", prtlocalFile);
OleDbConnection conexaoExcel = new OleDbConnection(sDBstrExcel);
conexaoExcel.Open();
DataTable dt = conexaoExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
DataSet output = new DataSet();
foreach (DataRow row in dt.Rows)
{
string sheet = row["TABLE_NAME"].ToString(); //Obtém o nome da planilha corrente
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conexaoExcel); //Obtém todas linhas da planilha corrente
cmd.CommandType = CommandType.Text;
DataTable outputTable = new DataTable(sheet); //Copia os dados da planilha para o DataTable
output.Tables.Add(outputTable);
new OleDbDataAdapter(cmd).Fill(outputTable);
}
conexaoExcel.Close();
return output;
}
But when I call the method does not return anything in the DataGridView...
public void testeImportExcel()
{
try
{
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Selecione o relatório do Detran";
fdlg.InitialDirectory = #"c:\";
//string endereco = fdlg.FileName;
//txtNomeArquivo.Text = fdlg.FileName;
fdlg.Filter = "Excel File (*.xlsx)|*.xlsx";
//fdlg.Filter = "Excel File (*.csv)|*.csv";
fdlg.FilterIndex = 1;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
myDtGridView.DataSource = MtdGetExcel(fdlg.FileName);
myDtGridView.AutoGenerateColumns = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Result:
Can you help me?
Here is my exact method that I have in production:
public DataTable ReadExcel(string fileName, string TableName)
{
DataTable dt = new DataTable();
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 8.0\"");
OleDbCommand cmd = new OleDbCommand("SELECT * FROM " + TableName, conn);
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while (!reader.IsClosed)
{
dt.Load(reader);
}
}
finally
{
conn.Close();
}
return dt;
}
I'm sure just by looking at it you can tell- this method takes in the fileName (or file path) of the Excel you're wanting to read from. Creates the connection string and command. Excel will be read like a database and its worksheets will be read like tables. TableName is the name of the worksheet (table). This method returns a DataTable that can be added to a DataSet if needed.

Don't close excel.exe when open it by oledb C#

I have a problem when I try to close excel file.I'm using OleDb to open excel file and then I close its. But it doesn't work.
OleDbConnection ole = new OleDbConnection(connString);
ole.Open();
comboBox1.DataSource = GetExcelSheetNames(filePath);
OleDbCommand cmd = new OleDbCommand("Select * from [" + comboBox1.SelectedValue.ToString() + "]", ole);
OleDbDataAdapter oledata = new OleDbDataAdapter();
oledata.SelectCommand = cmd;
DataSet ds = new DataSet();
oledata.Fill(ds);
DataTable datatable = ds.Tables[0];
StripEmptyRows(datatable);
dataGridView3.DataSource = datatable;
oledata.Dispose();
ole.Close();
ole = null;
ds.Dispose();
P/s: This is a GetExcelSheetName
private String[] GetExcelSheetNames(string excelFile)
{
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
String connString = "";
string[] fileSpit = filePath.Split('.');
try
{
if (filePath.Length > 1 && fileSpit[1] == "xls")
{
connString = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0";
}
else
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0";
}
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
return excelSheets;
}
catch (System.Exception ex)
{
return null;
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
Update: I use code,it works but not good.
private void ImportDialogBox_FormClosing(object sender, FormClosingEventArgs e)
{
HideImportDialogBox();
System.Windows.Forms.Application.Exit();
try
{
if (txtExcelFile.Text != null)
{
xlApp.Quit();
xlWorkbook.Close(true);
}
}
catch { }
finally //kill excel.exe
{
try
{
Process[] excelProcsNew = Process.GetProcessesByName("EXCEL");
foreach (Process procNew in excelProcsNew)
{
int exist = 0;
foreach (Process procOld in excelProcsOld)
{
if (procNew.Id == procOld.Id)
{
exist++;
}
}
if (exist == 0)
{
procNew.Kill();
}
}
}
catch { }
}
}

How to convert csv to datatable in c#, mvc

I'm converting .csv file to datatable like below.
string header = isFirstRowHeader ? "Yes" : "No";
string itinerarycsvfilePath = Path.GetDirectoryName(#"D:\projects\MSC cruise\MSCCruiseProjects\MsccruiseWithLogin\MsccruiseWithLogin\UnzippedFiles\itinff_gbr_eng.csv");
string filename = Path.GetFileName(#"D:\projects\MSC cruise\MSCCruiseProjects\MsccruiseWithLogin\MsccruiseWithLogin\UnzippedFiles\itinff_gbr_eng.csv");
string sql = #"SELECT * FROM [" + filename + "]";
using (OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + itinerarycsvfilePath +
";Extended Properties=\"Text;HDR=" + header + "\""))
using (OleDbCommand command = new OleDbCommand(sql, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable("ItineraryDetails");
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
then the result when I look with quick watch
Am I doing something wrong.I feel like that because table does not show like columns.
what can I do for that.
hope your help.
See code below
public class CSVReader
{
public DataSet ReadCSVFile(string fullPath, bool headerRow)
{
string path = fullPath.Substring(0, fullPath.LastIndexOf("\\") + 1);
string filename = fullPath.Substring(fullPath.LastIndexOf("\\") + 1);
DataSet ds = new DataSet();
try
{
if (File.Exists(fullPath))
{
string ConStr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}" + ";Extended Properties=\"Text;HDR={1};FMT=Delimited\\\"", path, headerRow ? "Yes" : "No");
string SQL = string.Format("SELECT * FROM {0}", filename);
OleDbDataAdapter adapter = new OleDbDataAdapter(SQL, ConStr);
adapter.Fill(ds, "TextFile");
ds.Tables[0].TableName = "Table1";
}
foreach (DataColumn col in ds.Tables["Table1"].Columns)
{
col.ColumnName = col.ColumnName.Replace(" ", "_");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return ds;
}
}

c# OleDbDataAdapter excel missing last row

GetExcelSheetNames:
static String[] GetExcelSheetNames(string excelFile, string extention)
{
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
string filepath= excelFile;// +; excelFile;
string Conn = "";
if (extention == "xls")
Conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath+ ";Extended Properties=Excel 8.0;";
else Conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath+ ";Extended Properties=Excel 12.0";
try
{
// Connection String. Change the excel file to the file you
// will search.
// Create connection object by using the preceding connection string.
objConn = new OleDbConnection(Conn);
// Open connection with the database.
objConn.Open();
// Get the data table containg the schema guid.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
return excelSheets;
}
catch (Exception ex)
{
return null;
}
finally
{
// Clean up.
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
GetTable:
private DataSet GetTable(string filepath, string extention)
{
string strConn;
if (extention == "xls")
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 8.0;";
}
else
{
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=Excel 12.0";
}
DataSet myDataSet = new DataSet();
OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [" + GetExcelSheetNames(filepath, extention)[0] + "]", strConn);
myCommand.Fill(myDataSet, "ExcelInfo");
if (myDataSet.Tables[0].Rows.Count > 0)
{
return myDataSet;
}
else return null;
}
I export excel data to datatable by using OleDbDataAdapter.
My both method (above side) works however last row is missing .
Where i miss exactly how can i get all rows from excel ?
Any help will be appreciated.
Thanks.

Excel c#.net retrieving data without opening excel in the background

I am trying to read a data in an excel sheet using C#, here is my code.
public void ReadExcel()
{
try
{
string sheetName = "Sheet1$A1:C6";
DataTable sheetTable = loadSingleSheet(#"C:\Users\..\Desktop\Sample.xls", sheetName);
}
catch (Exception e)
{
throw e;
}
}
private OleDbConnection returnConnection(string fileName)
{
return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 8.0;\"");
}
private DataTable loadSingleSheet(string fileName, string sheetName)
{
DataTable sheetData = new DataTable();
using (OleDbConnection conn = this.returnConnection(fileName))
{
conn.Open();
// retrieve the data using data adapter
OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "]", conn);
sheetAdapter.Fill(sheetData);
}
return sheetData;
}
But DataTable always get null value
Here it is how to do it using ODBC and ADO.Net
private void Form1_Load(object sender, EventArgs e)
{
try
{
string sheetName = "Sheet1$";// Read the whole excel sheet document
DataTable sheetTable = loadSingleSheet(#"C:\excelFile.xls", sheetName);
dataGridView1.DataSource = sheetTable;
string sheetNameWithRange = "Sheet1$A1:D10"; // Read excel sheet document from A1 cell to D10 cell values.
DataTable sheetTableWithRange = loadSingleSheet(#"C:\excelFile.xls",sheetNameWithRange);
dataGridView2.DataSource = sheetTableWithRange;
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message, "");
}
}
private OleDbConnection returnConnection(string fileName)
{
return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 8.0;\"");
}
private DataTable loadSingleSheet(string fileName, string sheetName)
{
DataTable sheetData = new DataTable();
using (OleDbConnection conn = this.returnConnection(fileName))
{
conn.Open();
// retrieve the data using data adapter
OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "]", conn);
sheetAdapter.Fill(sheetData);
}
return sheetData;
}

Categories