c# OleDbDataAdapter excel missing last row - c#

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.

Related

oledbConn.ServerVersion' threw an exception of type 'System.InvalidOperationException

In MVC Application While Connect with Excel gives an error
I just create a connection with excel and when try to open it's give error
oledbConn.ServerVersion' threw an exception of type
'System.InvalidOperationException
public DataTable Read(string filePath)
{
string extension = System.IO.Path.GetExtension(filePath).ToLower();
string connString = string.Empty;
if (extension.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'";
}
else if (extension.Trim() == ".xlsx")
{
//connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
//connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;Persist Security Info=False";
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'";
}
connString = string.Format(connString, filePath);
var dataTable = ConvertXSLXtoDataTable(filePath, connString);
return dataTable;
}
DataTable ConvertXSLXtoDataTable(string strFilePath, string connString)
{
OleDbConnection oledbConn = new OleDbConnection(connString);
DataTable dt = new DataTable();
try
{
oledbConn.Open();
using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn))
{
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
DataSet ds = new DataSet();
oleda.Fill(ds);
dt = ds.Tables[0];
}
}
catch
{
}
finally
{
oledbConn.Close();
}
return dt;
}

Problems reading all the lines of an excel with OLEDB and C#

I am developing a program to import excel spreadsheets with C # language, using the OLEDB component, when importing a spreadsheet with 100547 rows the program can only read 54046.
Follows the source code:
public class ReadExcel
{
public string ConnectionExcel(ExcelUpload excelUpload)
{
//connection String for xls file format.
if (excelUpload.fileExtension == ".xls")
{
excelUpload.excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelUpload.fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
//connection String for xlsx file format.
else if (excelUpload.fileExtension == ".xlsx")
{
excelUpload.excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelUpload.fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}else
{
excelUpload.excelConnectionString = "";
}
return excelUpload.excelConnectionString;
}
public DataTable readArqExcel(string excelConnectionString, DataSet ds)
{
//Create Connection to Excel work book and add oledb namespace
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
DataTable dt = new DataTable();
dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
//Numero de planilhas contidas no excel
String[] excelSheets = new String[dt.Rows.Count];
int count = 0;
//excel data saves in temp file here.
foreach (DataRow row in dt.Rows)
{
excelSheets[count] = row["TABLE_NAME"].ToString();
count++;
}
OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);
string query = string.Format("Select * from [{0}]", excelSheets[0]);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
{
dataAdapter.Fill(ds);
}
excelConnection.Close();
return ds.Tables[0];
}
I have tested IIS 8 (REMOTE SERVER) and IIS Express (Visual Studio local server), I noticed that on the IIS Express server the code works perfectly, but in IIS 8 the code ends up reading the file in half.
Is it some kind of web server configuration?
problem resolved, i altered string of connection OLEBD with MsExcel.
Alter parameter IMEX = 2 for IMEX = 1, as below
if (excelUpload.fileExtension == ".xls")
{
excelUpload.excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelUpload.fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
}
//connection String for xlsx file format.
else if (excelUpload.fileExtension == ".xlsx")
{
excelUpload.excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelUpload.fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\"";
}

Arabic letter data save to database as "?"

I'm uploading data to DB table using excel sheet
I'm uploading data to ProductStatisticsTemp table
In that table I have following columns
Product_ID
ProductNameEn
ProductNameAr
this the upload data POST method
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase file)
{
if (Request.Files["file"].ContentLength > 0)
{
string fileExtension = System.IO.Path.GetExtension(Request.Files["file"].FileName);
if (fileExtension == ".xls" || fileExtension == ".xlsx")
{
string fileLocation = Server.MapPath("~/Content/ExcelFiles/") + Request.Files["file"].FileName;
if (System.IO.File.Exists(fileLocation))
{
System.IO.File.Delete(fileLocation);
}
Request.Files["file"].SaveAs(fileLocation);
string excelConnectionString = string.Empty;
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
//connection String for xls file format.
if (fileExtension == ".xls")
{
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
//connection String for xlsx file format.
else if (fileExtension == ".xlsx")
{
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
//Create Connection to Excel work book and add oledb namespace
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
DataTable dt = new DataTable();
dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int t = 0;
//excel data saves in temp file here.
foreach (DataRow row in dt.Rows)
{
excelSheets[t] = row["TABLE_NAME"].ToString();
t++;
}
OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);
string query = string.Format("Select * from [{0}]", excelSheets[0]);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
{
dataAdapter.Fill(ds);
}
}
if (fileExtension.ToString().ToLower().Equals(".xml"))
{
string fileLocation = Server.MapPath("~/Content/ExcelFiles") + Request.Files["FileUpload"].FileName;
if (System.IO.File.Exists(fileLocation))
{
System.IO.File.Delete(fileLocation);
}
Request.Files["FileUpload"].SaveAs(fileLocation);
XmlTextReader xmlreader = new XmlTextReader(fileLocation);
// DataSet ds = new DataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
}
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string conn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection con = new SqlConnection(conn);
string query = "Insert into ProductStatisticsTemp(Product_ID,ProductNameEn,ProductNameAr) Values('" + ds.Tables[0].Rows[i][0] + "','" + ds.Tables[0].Rows[i][1] + "','" + ds.Tables[0].Rows[i][2] )";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
}
}
return RedirectToAction("FileUpload", "FileUpload");
}
But in here data saving smoothly , but ProductNameAr fields Arabic letters values save as "?"
ex: If excel value حساب التوفير للاستثمار Albrka
then its saving in database table as ???? ??????? ????????? Albrka
How to save as exact format in the excel sheet
ps. this ProductNameAr data type in Database table is NVARCHAR
You use non-Unicode string literals 'value' when you should use Unicode literals in the form N'value'
You better rewrite as parameterized SqlCommand passing the values using AddWithValue
string query = "Insert into ProductStatisticsTemp(Product_ID,ProductNameEn,ProductNameAr) Values(#Product_ID,#ProductNameEn,#ProductNameAr)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#Product_ID", ds.Tables[0].Rows[i][0]);
...etc...
You don't need to re-create and open the SqlConnection inside the loop

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;
}

Bind data from excel sheet to repeater or GridView

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 :)

Categories