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 { }
}
}
Related
So I am trying to delete some rows from DataGridView selecting a couple of them, but I cannot do it. I will explain it with the code.
if ((bool)dtrow.Cells[0].Value == true)
{
con = new SqlConnection(cs.DBConn);
con.Open();
int RowsAffected = 0;
string queryDelete = "DELETE FROM InfoFile WHERE FileName='" + dtrow.Cells[2].Value.ToString() + "'";
cmd = new SqlCommand(queryDelete);
cmd.Connection = con;
RowsAffected = cmd.ExecuteNonQuery();
if (RowsAffected > 0)
{
test();
}
else
{
MessageBox.Show("Records not found!", "Try again", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
The teste(); method will update the DataGridView after delete something.
public void test()
{
try
{
con = new SqlConnection(cs.DBConn);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(#"SELECT SelectedOrNot, Status, FileName, FileType, FileSize, FilePath,
Created, Modified, Access, PCName FROM InfoFile", con);
DataTable dt = new DataTable();
con = new SqlConnection(cs.DBConn);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(#"SELECT SelectedOrNot, Status, NomeFicheiro, TipoFicheiro, TamanhoFicheiro, CaminhoFicheiro,
Criado, Modificado, Acedido, NomePC FROM InfoFicheiro", con);
DataTable dt = new DataTable();
dataGridView1.DataSource = null;
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = false;
dataGridView1.Rows[n].Cells[1].Value = row[1];
dataGridView1.Rows[n].Cells[2].Value = row[2].ToString();
dataGridView1.Rows[n].Cells[3].Value = row[3].ToString();
dataGridView1.Rows[n].Cells[4].Value = row[4].ToString();
dataGridView1.Rows[n].Cells[5].Value = row[5].ToString();
dataGridView1.Rows[n].Cells[6].Value = row[6].ToString();
dataGridView1.Rows[n].Cells[7].Value = row[7].ToString();
dataGridView1.Rows[n].Cells[8].Value = row[8].ToString();
dataGridView1.Rows[n].Cells[9].Value = row[9].ToString();
if (dataGridView1.Rows.Count < 0)
{
int rowIndex = dataGridView1.Rows.Count - 1;
dataGridView1.Rows[rowIndex].Selected = true;
dataGridView1.CurrentCell = dataGridView1.Rows[rowIndex].Cells[0];
}
else if (dataGridView1.Rows.Count > 0)
{
int rowIndex = dataGridView1.Rows.Count - 1;
dataGridView1.Rows[rowIndex].Selected = true;
dataGridView1.CurrentCell = dataGridView1.Rows[rowIndex].Cells[0];
}
foreach (DataGridViewRow drow in dataGridView1.Rows)
{
drow.Height = 18;
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error\nDetalhes: " + ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
If I comment the test(); method it will remove the selected rows. If I use the teste(); method it will remove just one row but it will update.
So do you have any idea I could I solve it?
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.
I Planned to insert image in database. But there is some problem while inserting i.e (image format : input string was not in correct format). Please help me . Thanks in advance.
Error comes in this line -> int count = cmd.ExecuteNonQuery();
I have created the database with img (column name) Blob (datatype).
public partial class check1 : System.Web.UI.Page
{
MySqlConnection con = new MySqlConnection("server=localhost; database=esample; uid=root;");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridData();
}
}
protected void btnupload_Click(object sender, EventArgs e)
{
if (fileupload.HasFile)
{
int length = fileupload.PostedFile.ContentLength;
byte[] imgbyte = new byte[length];
HttpPostedFile img = fileupload.PostedFile;
img.InputStream.Read(imgbyte, 0, length);
string imagename = imgname.Text;
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO brand (imgname,img) VALUES (#imagename,#imagedata)", con);
cmd.Parameters.Add("#imagename", SqlDbType.VarChar).Value = imagename;
cmd.Parameters.Add("#imagedata", SqlDbType.Blob).Value = imgbyte;
int count = cmd.ExecuteNonQuery();
con.Close();
if(count==1)
{
BindGridData();
imgname.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + imagename + " image inserted successfully')", true);
}
}
}
private void BindGridData()
{
MySqlConnection con = new MySqlConnection("server=localhost; database=esample; uid=root;");
MySqlCommand command = new MySqlCommand("SELECT imgname,img,bid from brand", con);
MySqlDataAdapter daimages = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
gvImages.DataSource = dt;
gvImages.DataBind();
gvImages.Attributes.Add("bordercolor", "black");
}
}
Using a class named Player with the id, name and photo values.
public static bool createUser(Player player)
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO tbuser (id,sName,lbFoto) VALUES (#id,#name,#foto)", dbConnection);
cmd.Parameters.AddWithValue("#id", player.id).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("#name", player.Name).DbType = DbType.String;
cmd.Parameters.AddWithValue("#foto", player.Image).DbType = DbType.Binary;
try
{
if (dbConnection.State == ConnectionState.Closed)
dbConnection.Open();
cmd.ExecuteNonQuery();
dbConnection.Close();
return true;
}
}
catch { }
finaly
{
if (dbConnection.State == ConnectionState.Open)
dbConnection.Close();
}
return false;
}
Then for retrieval the data:
public static Player loadUser(string ID)
{
var table = Select(dbConnection, "tbuser", "id = " + ID);
Player player = new Player();
foreach (DataRow row in table.Rows)
{
player.id = (int)row[0];
player.Name = row[1].ToString();
player.Image = (byte[])row[2];
return player;
}
return null;
}
The function Select. This is an extra ;)
public static DataTable Select(MySqlConnection con, string tableName, string expressionWhere)
{
string text = string.Format("SELECT * FROM {0} WHERE {1};", tableName, expressionWhere);
MySqlDataAdapter cmd = new MySqlDataAdapter(text, con);
DataTable table = new DataTable();
if (con.State == ConnectionState.Closed)
con.Open();
try
{
cmd.Fill(table);
}
catch (Exception){}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
return table;
}
I am importing an Excel sheet into a SQL Server database. The Excel sheet contains 3 columns
id|data|passport
I am using SqlBulkCopy
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
string[] filePaths = null;
string strFileType = null;
string strFileName = null;
string strNewPath = null;
int fileSize;
int flag=0;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
fileSize = FileUpload1.PostedFile.ContentLength / 1024;
//EXCEL DETAILS TABLE
con.Open();
//=========================================
DataTable dt8 = new DataTable();
SqlCommand cmd8 = new SqlCommand("insert into exceldetails (name,type,details,size)" + "values(#name,#type,#details,#size)", con);
cmd8.Parameters.Add("#name", SqlDbType.VarChar).Value = strFileName;
cmd8.Parameters.Add("#type", SqlDbType.VarChar).Value = strFileType;
cmd8.Parameters.Add("#details", SqlDbType.VarChar).Value = DateTime.Now;
cmd8.Parameters.Add("#size", SqlDbType.Int).Value = fileSize;
cmd8.ExecuteNonQuery();
con.Close();
try
{
SqlDataAdapter da8 = new SqlDataAdapter(cmd8);
da8.Fill(dt8);
}
catch { }
//=========================================
//CHOOSING EXCEL CONNECTIONSTRING
string excelConnectionString = "";
switch (strFileType)
{
case ".xls":
excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strNewPath + "; Extended Properties=Excel 8.0;");
break;
case ".xlsx":
{
excelConnectionString = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + strNewPath + "; Extended Properties=Excel 12.0 Xml;");
break;
}
}
//===================================
//PRE EXCEL COUNT
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
connection.Open();
OleDbCommand command = new OleDbCommand("Select ID,Data,passport FROM [Sheet1$]", connection);
OleDbCommand command1 = new OleDbCommand("select count(*) from [Sheet1$]", connection);
//Sql Server Table DataTable
DataTable dt4 = new DataTable();
SqlCommand cmd4 = new SqlCommand("select * from excelsheet", con);
try
{
SqlDataAdapter da4 = new SqlDataAdapter(cmd4);
da4.Fill(dt4);//sql table datatable
}
catch { }
//===============================
//excelsheet datatable
DataTable oltlb = new DataTable();
OleDbCommand olcmd = new OleDbCommand("select * from [Sheet1$]", connection);
try
{
OleDbDataAdapter olda = new OleDbDataAdapter(olcmd);
olda.Fill(oltlb); //excel table datatable
}
catch { }
//==============================
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=DITSEC3;Initial Catalog=test;Integrated Security=True";
con.Open();
DataTable dt7 = new DataTable();
dt7.Load(dr);
DataRow[] ExcelRows = new DataRow[dt7.Rows.Count];
DataColumn[] ExcelColumn = new DataColumn[dt7.Columns.Count];
//=================================================
for (int i1 = 0; i1 < ExcelRows.Length; i1++)
{
string a = ExcelRows[i1]["passport"].ToString();
char a1 = a[0];
if (a1 >= 'A' || a1 <= 'Z')
{
Label12.Text = "CAPITAL";
break;
}
else
{
Label12.Text = "notgood";
flag = flag + 1;
}
}
//=========================================================
if (flag == 0)
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
dt7.Rows.CopyTo(ExcelRows, 0);
//==========================================================================================
for (int i = 0; i < ExcelRows.Length; i++)
{
if (ExcelRows[i]["passport"] == DBNull.Value)
{
ExcelRows[i]["passport"] = 0;
}
}
bulkCopy.WriteToServer(ExcelRows);
//==========================================================================================
for (int i = 0; i < ExcelRows.Length; i++)
{
if (ExcelRows[i]["data"] == DBNull.Value)
{
// Include any actions to perform if there is no date
//ExcelRows[i]["data"] = Convert.ToDateTime("0");
}
else
{
DateTime oldDate = Convert.ToDateTime(ExcelRows[i]["data"]).Date;
DateTime newDate = Convert.ToDateTime(oldDate).Date;
ExcelRows[i]["data"] = newDate.ToString("yyyy/MM/dd");
}
}
//==========================================================================================
}
//======
}
else
{
Label13.Text = "Wrong Format";
}
}
}
}
}
ERROR AT :
string a = ExcelRows[i1]["passport"].ToString();
ERROR:
Object reference not set to an instance of an object.
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 :)