good day, im reading data from excel file and showing it to gridview. but errors says "The Microsoft Jet database engine cannot open the file ''. It is already opened exclusively by another user, or you need permission to view its data."
what i have done:
give full access write to folder for IUSR, NETWORK_SERVICE, NETWORK, EVERYONE, USERS AND ADMIN
thank you in advance.
String filePath = txtBbSource.Text;
String sheetName = txtSheetName.Text;
string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;'";
OleDbConnection con = new OleDbConnection(constr);
OleDbDataAdapter sda = new OleDbDataAdapter("Select * from [" + sheetName + "$]", con);
DataTable dt = new DataTable();
sda.Fill(dt);
gridBalances.DataSource = dt;
private void FillGrid(string FilePath, string Extension)
{
string conStr = "";
DataTable dt = new DataTable();
/*Add below Commented in Webconfig*/
/* <add name ="Excel03ConString"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};
Extended Properties='Excel 8.0;HDR={1}'"/>
<!--connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};
Extended Properties='Excel 8.0;HDR={1}'"/>-->
<add name ="Excel07ConString"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};
Extended Properties='Excel 8.0;HDR={1}'"/>
* */
switch (Extension)
{
case ".xls": //Excel 97-03
conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07
conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
break;
}
conStr = String.Format(conStr, FilePath, "Yes");
OleDbConnection connExcel = new OleDbConnection(conStr);
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
cmdExcel.Connection = connExcel;
try
{
int m = 1;
//Get the name of First Sheet
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
//Read Data from First Sheet
connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
//oda.SelectCommand = cmdExcel;
//oda.Fill(dt);
// connExcel.Close();
DataTable myColumns = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, SheetName, null });
foreach (DataRow dtRow in myColumns.Rows)
{
if (dtRow["COLUMN_NAME"].ToString() == "Sr No" && dtRow["ORDINAL_POSITION"].ToString() == "1")
{
m++;
}
else if (dtRow["COLUMN_NAME"].ToString() == "Task Name" && dtRow["ORDINAL_POSITION"].ToString() == "2")
{
m++;
}
}
/*column count in excel*/
if (m < 2)
{
lblErrMsg.Visible = true;
lblErrMsg.Text = "Selected file is not in required template format.";
return;
}
oda.SelectCommand = cmdExcel;
oda.Fill(dt);
connExcel.Close();
}
catch (Exception ex)
{
lblErrMsg.Visible = true;
lblErrMsg.Text = "Selected file is not in required template format.";
return;
}
DataTable dt_grd1 = new DataTable();
DataRow drnewrow = null;
//upload_plan = 1;
foreach (DataRow dtRow in dt.Rows)
{
if (dtRow["Sr No"].ToString() == "" && dtRow["Task Name"].ToString() != "")
{
dt_grd1.Columns.Add(new DataColumn("ID", typeof(string)));
dt_grd1.Columns.Add(new DataColumn("TASK_NAME", typeof(string)));
}
try
{
drnewrow = dt_grd1.NewRow();
drnewrow["ID"] = "";
drnewrow["TASK_NAME"] = dtRow["Task Name"].ToString();
dt_grd1.Rows.Add(drnewrow);
}
catch (Exception ex)
{
//lblError.Visible = true;
////lblError.Text = ex.Message;// "Authentication failed. Please try later.";
//lblError.Text = DataInteraction.Constants.EXCEPTION;
}
}
/*Using Linq Find same TASK_NAME present in Excel*/
if (dt_grd1.Rows.Count >= 1)
{
var Taskresult = from c in dt_grd1.AsEnumerable()
group c by new
{
TaskName2 = c.Field<dynamic>("TASK_NAME"),
} into g
where g.Count() > 1
select new
{
g.Key.TaskName2,
// g.Key.Pin,
Noofrec = g.Count()
};
if (Taskresult.ToList().Count > 0)
{
lblErrMsg.Visible = true;
div_err_log.Visible = false;
lblErrMsg.Text = "Task with same Name not allowed.";
return;
}
}
grdTaskDataCat1.DataSource = dt_grd1;
grdTaskDataCat1.DataBind();
/*End 13th Jan'17*/
lblErrMsg.Visible = true;
lblErrMsg.Text = "Please confirm the details uploaded and press save to complete the upload of Bid plan.";
return;
}
Related
I have a aspx page,which allows you to upload an excel template and content from that template are fetched to a datatable and then updated in SQL Server Database.
OLEDB data provider is used.
Conn =new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;
Data Source={0};Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;'", filename))
In above connection string, data source is given as Data Source ={0} what does it mean?
Here is the code behind for UPLOAD button.
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.FileName.ToString() == "")
{
lblMessage.Text = "Please select the File to Upload";
lblMessage.ForeColor = System.Drawing.Color.Red;
return;
}
string filename = Server.MapPath("Temp/" + FileUpload1.FileName.ToString());
FileUpload1.SaveAs(filename);
HttpPostedFile postedFile = this.FileUpload1.PostedFile;
OleDbConnection Conn = null;
OleDbDataAdapter DA;
DataTable DT = new DataTable();
DataTable tempDT = new DataTable();
if (Path.GetExtension(postedFile.FileName) == ".xls")
{
Conn = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;'", filename));
OleDbCommand excelCmd = new OleDbCommand();
string sheet_Name = "";
excelCmd.Connection = Conn;
excelCmd.Connection.Open();
DT = excelCmd.Connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sheet_Name = DT.Rows[0]["TABLE_NAME"].ToString();
excelCmd.Connection.Close();
if (sheet_Name == "")
{
//Throw Excption if Sheet is not present in file
}
DA = new OleDbDataAdapter(string.Format("select * from [{0}]", sheet_Name), Conn);
DA.Fill(DT);
string Qno = string.Empty;
string Qdesc = string.Empty;
string Header = string.Empty;
int Dorder;
string eAlert = string.Empty;
foreach (DataRow dr in DT.Rows)
{
if (!DT.Columns.Contains("QuestionNo"))
{
lblMessage.Text = "QuestionNo ColumnName Mismatching";
lblMessage.ForeColor = System.Drawing.Color.Red;
grd_Questions.DataBind();
return;
}
else if (!DT.Columns.Contains("QuestionDesc"))
{
lblMessage.Text = "QuestionDesc ColumnName Mismatching";
lblMessage.ForeColor = System.Drawing.Color.Red;
grd_Questions.DataBind();
return;
}
else if (!DT.Columns.Contains("Type"))
{
lblMessage.Text = "Type ColumnName Mismatching";
lblMessage.ForeColor = System.Drawing.Color.Red;
grd_Questions.DataBind();
return;
}
else if (!DT.Columns.Contains("e-Alert"))
{
lblMessage.Text = "e-Alert ColumnName Mismatching";
lblMessage.ForeColor = System.Drawing.Color.Red;
grd_Questions.DataBind();
return;
}
else if (!DT.Columns.Contains("DisplayOrder"))
{
lblMessage.Text = "DisplayOrder ColumnName Mismatching";
lblMessage.ForeColor = System.Drawing.Color.Red;
grd_Questions.DataBind();
return;
}
else
{
PQ.updateQuestion();
}
}
It means that your data source will be your excel file. The '{0}' part will be replaced by the 'filename' (after Comma part) during execution. So that your excel file will act as a database.
("Provider={0};Data Source={1};Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;'", Microsoft.ACE.OLEDB.12.0, filename)
This would also work.
I'm initially populating my DataGridView with data from Excel Sheet.
private void btnChooseAndRead_Click(object sender, EventArgs e)
{
Refresh();
string filePath = string.Empty;
string fileExt = string.Empty;
OpenFileDialog file = new OpenFileDialog();//open dialog to choose file
if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK)//if there is a file choosen by the user
{
filePath = file.FileName;//get the path of the file
fileExt = Path.GetExtension(filePath);//get the file extension
if (fileExt.CompareTo(".xls") == 0 || fileExt.CompareTo(".xlsx") == 0)
{
try
{
cmbSheetName.Text = "";
cmbSheetName.Items.Clear();
string[] names = GetExcelSheetNames(file.FileName);
//Populate Combobox with Sheet names
foreach (string name in names)
{
cmbSheetName.Items.Add(name);
}
DataTable dtExcel = new DataTable();
dtExcel = ReadExcel(filePath, fileExt); //read excel file
cmbSheetName.Visible = true;
lblFileName.Text = file.SafeFileName.ToString();
BindingSource theBindingSource = new BindingSource();
dgvViewData.Visible = true;
dgvViewData.DataSource = dtExcel;
//dgvViewData.ColumnDisplayIndexChanged = true;
//cmbSheetName_SelectedIndexChanged(sender, e);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
else
{
MessageBox.Show("Please choose .xls or .xlsx file only.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);//custom messageBox to show error
}
}
}
public DataTable ReadExcel(string fileName, string fileExt)
{
string conn = string.Empty;
DataTable dtexcel = new DataTable();
if (fileExt.CompareTo(".xls") == 0)//compare the extension of the file
conn = #"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';";//for below excel 2007
else
conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';";//for above excel 2007
using (OleDbConnection con = new OleDbConnection(conn))
{
try
{
OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select * from [Sheet1$]", con);//here we read data from sheet1
oleAdpt.Fill(dtexcel);//fill excel data into dataTable
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
return dtexcel;
}
Which works perfectly fine, now the Excel file that I'm reading from has more than one sheets.
I also have a combobox populating the Sheetnames.
What needs to happen is that when the user selects for example "Sheet5" from the combo I want to refresh the Gridview with the selected sheet details. How do I do this? How do I even know that all sheets are all in the Gridview?
I did not test this thoroughly, but it appears to work correctly. Assuming you are using OLEDB... basically the code below uses a DataSet to hold all the worksheets. While gathering the worksheets I also create a simple List<string> to hold the names of each worksheet to display into the combo box. Since the worksheet and the combo box are added at the same time, we can use the combo boxes selected index to identify the proper worksheet (data table in the data set) to display. The names of worksheets have a “$” sign in their name. I removed this “$” when displayed to the combo box.
The code below is a form with a DataGridView to display the data tables, a ComboBox to select a data table and a Label to give info about the currently selected data table. Hope this helps.
public partial class Form1 : Form {
private string Excel07ConString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\YourFilePath\YourFile.xls;Extended Properties='Excel 12.0 Xml;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text'";
string sheetName;
DataSet ds;
List<string> comboBoxData = new List<string>();
public Form1() {
InitializeComponent();
SetDataTablesFromExcel();
dataGridView1.DataSource = ds.Tables[0];
comboBox1.DataSource = comboBoxData;
label1.Text = "TableName: " + ds.Tables[0].TableName + " has " + ds.Tables[0].Rows.Count + " rows";
}
private void SetDataTablesFromExcel() {
ds = new DataSet();
using (OleDbConnection con = new OleDbConnection(Excel07ConString)) {
using (OleDbCommand cmd = new OleDbCommand()) {
using (OleDbDataAdapter oda = new OleDbDataAdapter()) {
cmd.Connection = con;
con.Open();
DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
for (int i = 0; i < dtExcelSchema.Rows.Count; i++) {
sheetName = dtExcelSchema.Rows[i]["TABLE_NAME"].ToString();
DataTable dt = new DataTable();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
oda.SelectCommand = cmd;
oda.Fill(dt);
dt.TableName = sheetName;
comboBoxData.Add(sheetName.Replace("$", ""));
ds.Tables.Add(dt);
}
}
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
int index = comboBox1.SelectedIndex;
dataGridView1.DataSource = ds.Tables[index];
label1.Text = "TableName: " + ds.Tables[index].TableName + " has " + ds.Tables[index].Rows.Count + " rows";
}
}
For example i have in excel file:
colname1 colname2 colname3
1 2 3
4 2 4
5 6 4
6 1 2
This is part of my code :
public IList<Range> GetColVal(string _path)
{
IList<Range> rowList= new List<Range>();
System.Data.DataTable tableExcel = new System.Data.DataTable();
FileInfo fileInfo = new FileInfo(_path);
app = new Microsoft.Office.Interop.Excel.Application();
wb = app.Workbooks.Open(_path, Type.Missing);
sheet = (Worksheet)wb.Sheets[1];
Range excelRange = sheet.UsedRange;
int colCount = excelRange.Columns.Count;
int rowCount = excelRange.Rows.Count;
Range tmpVar;
for (int i = 1; i <= rowCount; i++)
{
tmpVar = sheet.Rows[i];
rowList.Add(tmpVar);
}
return rowList;
}
I'd like to get field by column name from each row while iterate it by foreach
eg.
foreach(var a in ListRows)
{
a["colname1"] ...
}
How to contain col name in each row ?
I did this
static DataTable ExcelToDataTable(string FilePath, string Extension, string isHDR)
{
string conStr = "";
switch (Extension)
{
case ".xls": //Excel 97-03
conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'";
break;
case ".xlsx": //Excel 07
conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}";
break;
}
conStr = String.Format(conStr, FilePath, isHDR);
OleDbConnection connExcel = new OleDbConnection(conStr);
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmdExcel.Connection = connExcel;
//Get the name of First Sheet
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
//Read Data from First Sheet
connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
oda.Fill(dt);
connExcel.Close();
return dt;
}
an use it like this
DataTable dt = ExcelToDataTable(#"C:\Users\Nikhil\Desktop\1.xls", ".xls", "true");
Then you can loop over the DataTable with Column Names.
Please can you help me with my actually script. I have done select from excel file but now i dont know how can i added value to my lists. I get data from more files together not only from one.
Here is my actually scripts:
Base button initiate event for read.
private void next_Click(object sender, EventArgs e)
{
for (int i = 0; i < UniqueValue.traceToFile.Count; i++)
{
ReadFromExcel read = new ReadFromExcel();
read.ReadData(UniqueValue.traceToFile[i]);
}
}
After next step is this:
class ReadFromExcel : Config
{
public void ReadData(string fullpath)
{
DataSet da = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter();
string cell = "C7";
string name = "List1";
string FileName = fullpath;
string _ConnectionString = string.Empty;
string _Extension = Path.GetExtension(FileName);
// Checking for the extentions, if XLS connect using Jet OleDB
if (_Extension.Equals(".xls", StringComparison.CurrentCultureIgnoreCase))
{
_ConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0};Extended Properties=Excel 8.0", FileName);
}
// Use ACE OleDb
else if (_Extension.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase))
{
_ConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", FileName);
}
OleDbConnection con = new OleDbConnection(_ConnectionString);
string strCmd = "SELECT * FROM [" + name + "$" + cell + "]";
OleDbCommand cmd = new OleDbCommand(strCmd, con);
try
{
con.Open();
da.Clear();
adapter.SelectCommand = cmd;
adapter.Fill(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
con.Close();
}
}
}
Now I need that this result to be written to my list. i reading only one cells from every files.
List for result is
public static List<int> money = new List<int>();
I really thanks for all answers which can help me.
I think below code will help you.
In this example dt, dt2 and dt3 will consider return from your function ReadData function which have datatable from excel.
public static List<int> money = new List<int>();
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(Int32));
dt.Columns.Add("Name");
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["ID"] = 1;
dt.Rows[dt.Rows.Count - 1]["Name"] = "Test1";
DataTable dt2 = new DataTable();
dt2.Columns.Add("ID", typeof(Int32));
dt2.Columns.Add("Name");
dt2.Rows.Add();
dt2.Rows[dt2.Rows.Count - 1]["ID"] = 2;
dt2.Rows[dt2.Rows.Count - 1]["Name"] = "Test2";
DataTable dt3 = new DataTable();
dt3.Columns.Add("ID", typeof(Int32));
dt3.Columns.Add("Name");
dt3.Rows.Add();
dt3.Rows[dt3.Rows.Count - 1]["ID"] = 3;
dt3.Rows[dt3.Rows.Count - 1]["Name"] = "Test2";
money = (from row in dt.AsEnumerable() select Convert.ToInt32(row["ID"])).ToList();
money.AddRange((from row in dt2.AsEnumerable() select Convert.ToInt32(row["ID"])).ToList());
money.AddRange((from row in dt3.AsEnumerable() select Convert.ToInt32(row["ID"])).ToList());
}
Excel.Application excel;
Excel.Workbook wb;
Excel.Worksheet sh;
DataTable dt=new DataTable();
excel = new Excel.Application();
excel.Visible = true;
wb = excel.Workbooks.Open("File Path");
sh = wb.Sheets.Add();
sh.Name = "Data";
count = 2;
sh.Cells[count, "A"].Value2 = "Column Name 1";
sh.Cells[count, "B"].Value2 = "Column Name 2";
sh.Cells[count, "C"].Value2 = "Column Name 3";
sh.Cells[count, "D"].Value2 = "Column Name 4";
sh.Cells[count, "E"].Value2 = "Column Name 5";
sh.Range["A" + count + "", "E" + count + ""].Font.Size = 12;
sh.Range["A" + count + "", "E" + count + ""].Borders.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
sh.Range["I2"].WrapText = true;
try
{
con.Open();
da.Clear();
adapter.SelectCommand = cmd;
adapter.Fill(dt);
foreach (DataRow row in dt.Rows)
{
sh.Cells[count, "A"].Value2 = row["Column Name"].ToString();
sh.Cells[count, "B"].Value2 = row["Column Name"].ToString();
sh.Cells[count, "C"].Value2 = row["Column Name"].ToString();
sh.Cells[count, "D"].Value2 = row["Column Name"].ToString();
sh.Cells[count, "E"].Value2 = row["Column Name"].ToString();
}
wb.SaveAs("File Path" + "File Nmae" + ".xls");
excel.Workbooks.Close();
excel.Quit();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
con.Close();
}
I'm using these connection strings, depending on the extension of the file:
For 2003 : Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Excel 8.0;
For 2007 : Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;
Here is to get the connection.
string con_excel = "";
switch (Extension.ToLower())
{
case ".xls":
con_excel = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx":
con_excel = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
break;
}
con_excel = con_excel.Replace("filename", filePath);
The following is the code to generate excel file.
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
oXL = new Excel.Application();
oXL.Visible = false;
oXL.SheetsInNewWorkbook = 1;
oWB = (Excel._Workbook)(oXL.Workbooks.Add());
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
try
{
string[] colNames = new string[dataTable.Columns.Count];
int col = 0;
foreach (DataColumn dc in dataTable.Columns)
colNames[col++] = dc.ColumnName;
char lastColumn = (char)(65 + dataTable.Columns.Count - 1);
oSheet.get_Range("A1", lastColumn + "1").Value2 = colNames;
oSheet.get_Range("A1", lastColumn + "1").Font.Bold = true;
oSheet.get_Range("A1", lastColumn + "1").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
DataRow[] dr = dataTable.Select();
string[,] rowData = new string[dr.Count<DataRow>(), dataTable.Columns.Count + 1];
int rowCnt = 0;
foreach (DataRow row in dr)
{
for (col = 0; col < dataTable.Columns.Count; col++)
{
rowData[rowCnt, col] = row[col].ToString();
}
rowCnt++;
}
rowCnt++;
oSheet.get_Range("A2", lastColumn + rowCnt.ToString()).Value = rowData;
oXL.Visible = false;
oXL.UserControl = true;
String sNewFolderName = "Report_" + intReportId;
filename = Server.MapPath("Your Report\\" + sNewFolderName + DateTime.Now.ToString("dd-MM-yyyy_hh-mm-ss") + Extension);
oSheet.SaveAs(filename);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWB);
oXL.Quit();
Marshal.ReleaseComObject(oSheet);
Marshal.ReleaseComObject(oWB);
Marshal.ReleaseComObject(oXL);
oSheet = null;
oWB = null;
oXL = null;
GC.GetTotalMemory(false);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.GetTotalMemory(true);
//The excel is created and opened for insert value. We most close this excel using this system
Process[] localByName = Process.GetProcessesByName("EXCEL");
foreach (Process process in localByName)
{
process.Kill();
}
2007 file format is ok.
I tried to upload the 2003(.xls) excel file and then also generate 2003(.xls) format. But when i open that file, i got the following error.
The file you are trying to open "FileName.xls" in a different format than specified file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?
Is this because of connection string ?
Try this Code upload Excel 2003 and 2007 file
if (filenam.ToString() == ".xls")
{ constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathnam + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""; }
else if (filenam.ToString() == ".xlsx")
{ constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathnam + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\""; }
else { Response.Write("<script>alert('Load Excel file Only')</script>"); }
string Qry = "SELECT [Customer], [Project], [Contact], [Designation], [Phone], [EmailID],[Region] FROM [Sheet1$]";
OleDbConnection conn = new OleDbConnection(constr);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(Qry, conn);
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
if (dt != null && dt.Rows.Count > 0)
{
gv_upload.DataSource = dt;
gv_upload.DataBind();
}
da.Dispose(); conn.Close(); conn.Dispose();