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();
Related
I read excel but dataGridView show data than lines excel file, So I can't write datagridview.Rowcount(). I use the below given code to read the excel file.
Code:
filePath = txtExcelFile.Text;
string[] fileSpit = filePath.Split('.');
if (filePath.Length > 1 && fileSpit[1] == "xls")
{
connString = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=No'";
}
else
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0;HDR=No'";
}
OleDbCommand cmd = new OleDbCommand(#"Select * from [" +comboBox1.SelectedValue.ToString() + "]", ole);
OleDbDataAdapter oledata = new OleDbDataAdapter();
oledata.SelectCommand = cmd;
DataSet ds = new DataSet();
oledata.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
Either strip out the blank lines from the data table before assigning it to the grid:
private DataTable StripEmptyRows(DataTable dt)
{
List<int> rowIndexesToBeDeleted = new List<int>();
int indexCount = 0;
foreach(var row in dt.Rows)
{
var r = (DataRow)row;
int emptyCount = 0;
int itemArrayCount = r.ItemArray.Length;
foreach(var i in r.ItemArray) if(string.IsNullOrWhiteSpace (i.ToString())) emptyCount++;
if(emptyCount == itemArrayCount) rowIndexesToBeDeleted.Add(indexCount);
indexCount++;
}
int count = 0;
foreach(var i in rowIndexesToBeDeleted)
{
dt.Rows.RemoveAt(i-count);
count++;
}
return dt;
}
Or do your own row count ignoring blank rows.
I'm having an issue reading an excel file onto a datagridview. After running the application, it keeps telling me
"The process cannot access the file
'C:\Users\emmanuel.adefuye\Documents\ExcelTestFile.xlsx' because it is
being used by another process"
private void OpenExcelFile_Click(object sender, EventArgs e)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#"C:\\Users\\emmanuel.adefuye\\Documents\\ExcelTestFile.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
{
//String name = "First Name";
OpenFileDialog selectedFile = new OpenFileDialog();
selectedFile.ShowDialog();
selectedFile.OpenFile();
String constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
"C:\\Users\\emmanuel.adefuye\\Documents\\ExcelTestFile.xlsx" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + selectedFile.SafeFileName + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
}
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
//iterate over the rows and columns and print to the console as it appears in the file
//excel is not zero based!!
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
//new line
if (j == 1)
Console.Write("\r\n");
//write the value to the console
if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");
}
}
//cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.ReleaseComObject(xlRange);
Marshal.ReleaseComObject(xlWorksheet);
//close and release
xlWorkbook.Close();
Marshal.ReleaseComObject(xlWorkbook);
//quit and release
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
}`
There are a few different ways to read the data and manipulate it, but for your core issue of
"The process cannot access the file
'C:\Users\emmanuel.adefuye\Documents\ExcelTestFile.xlsx' because it is
being used by another process"
Your issue is that you're opening the file here
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#"C:\\Users\\emmanuel.adefuye\\Documents\\ExcelTestFile.xlsx");
And then again attempting to access it here
OpenFileDialog selectedFile = new OpenFileDialog();
selectedFile.ShowDialog();
selectedFile.OpenFile();
String constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
"C:\\Users\\emmanuel.adefuye\\Documents\\ExcelTestFile.xlsx" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
You could just use this great nuget package:
https://www.nuget.org/packages/NPOI/
and read excel like that:
public static XSSFWorkbook ReadExcelFile(string strFilePath)
{
XSSFWorkbook hssfwb;
using (FileStream file = new FileStream(strFilePath, FileMode.Open, FileAccess.Read))
{
hssfwb = new XSSFWorkbook(file);
}
return hssfwb;
}
private void OpenExcelFile_Click(object sender, EventArgs e)
{
var dt = ReadExcelFile(#"C:\\Users\\emmanuel.adefuye\\Documents\\ExcelTestFile.xlsx");
}
I am trying to fetch data from excel using below C# code. I am getting the value from two
columns into single variable(str).
I want that value into different variables.So that i can send that value at runtime for two different statements.
How to bring them into two different variable?
string currentSheet = "Sheet1";
excelApp = new Excel.Application();
//Opening/adding Excel file
excelWorkbook = excelApp.Workbooks.Add(workbookPath);
excelSheets = excelWorkbook.Sheets;
excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
//Gives the used cells in the sheet
range = excelWorksheet.UsedRange;
for (rowCnt = 1; rowCnt <= range.Rows.Count; rowCnt++)
{
for (colCnt = 1; colCnt <= range.Rows.Count;colCnt++)
{
str = (string)(range.Cells[rowCnt,colCnt] as Excel.Range).Value2;
System.Console.WriteLine(str);
}
}
string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
OleDbConnection con = new OleDbConnection(Connection);
OleDbCommand command = new OleDbCommand();
System.Data.DataTable dt = new System.Data.DataTable();
OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$]", con);
myCommand.Fill(dt);
con.Close();
for (rowCnt = 1; rowCnt <= range.Rows.Count; rowCnt++)
{
string Charity = (string)(range.Cells[rowCnt, 1] as Excel.Range).Value;
string Country = (string)(range.Cells[rowCnt, 2] as Excel.Range).Value;
System.Console.WriteLine(Charity + " --- " + Country);
}
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;
}
Hi guys! I encountered a problem is that I have difficulty reading this Excel file into data grid view as shown above. Any help will be greatly appreciated. Thanks.
These were my codes to read Excel file but there's a error that I have difficulty troubleshooting it.
private void btnSearch_Click(object sender, EventArgs e)
{
Excel.Workbook workbook;
Excel.Worksheet NwSheet;
Excel.Range ShtRange;
Microsoft.Office.Interop.Excel.Application ExcelObj = new Microsoft.Office.Interop.Excel.Application();
OpenFileDialog filedlgExcel = new OpenFileDialog();
filedlgExcel.Title = "Select file";
filedlgExcel.InitialDirectory = #"c:\";
filedlgExcel.FileName = txtFileName.Text;
filedlgExcel.Filter = "Excel Sheet(*.xlsx)|*.xlsx|All Files(*.*)|*.*";
filedlgExcel.FilterIndex = 1;
filedlgExcel.RestoreDirectory = true;
if (filedlgExcel.ShowDialog() == DialogResult.OK)
{
workbook = ExcelObj.Workbooks.Open(filedlgExcel.FileName);
NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
ShtRange = NwSheet.UsedRange; //gives the used cells in sheet
//Reading Excel file.
//Creating dataTable to read the containt of the Sheet in File.
//Set header name
for (int Cnum = 1; Cnum <= ShtRange.Columns.Count; Cnum++)
{
dt.Columns.Add(new DataColumn((ShtRange.Cells[1, Cnum] as Excel.Range).Value2.ToString()));
}
dt.AcceptChanges();
//store coumn names to array
string[] columnNames = (from dc in dt.Columns.Cast<DataColumn>() select dc.ColumnName).ToArray();
//populate fields
for (int Rnum = 2; Rnum <= ShtRange.Rows.Count; Rnum++)
{
DataRow dr = dt.NewRow();
for (int Cnum = 1; Cnum <= ShtRange.Columns.Count; Cnum++)
{
dr[Cnum - 1] = (ShtRange.Cells[Rnum, Cnum] as Excel.Range).Value2.ToString();
}
dt.Rows.Add(dr);
dt.AcceptChanges();
}
workbook.Close(true, Missing.Value, Missing.Value);
ExcelObj.Quit();
foreach (DataRow dr in dt.Rows)
{
string strEmployee = dr["Employee Name"].ToString();
obj1 = new List<employeeschedule>();
for (int i = 1; i < dt.Columns.Count; i++)
{
string period = dr[i].ToString();
string[] split = period.Split('–');
employeeschedule es = new employeeschedule();
string day = columnNames[i];
if (split[0] == "REST")
{
es.day = day;
es.startTime = "0000";
es.endTime = "0000";
es.restDay = "Yes";
}
if (split[0] == "OFF")
{
es.day = day;
es.startTime = "0000";
es.endTime = "0000";
es.restDay = "Yes";
}
else
{
es.day = day;
es.startTime = split[0];
es.endTime = split[1];
es.restDay = "No";
}
obj1.Add(es);
}
dict.Add(strEmployee, obj1);
dgvEmployeeShift.DataSource = dt;
}
}
}
The error falls on this part:
dt.Columns.Add(new DataColumn((ShtRange.Cells[1, Cnum] as Excel.Range).Value2.ToString()));
It states that "Cannot perform runtime binding on a null reference".
I love using Interop when automating Excel but for your requirement why not use OleDb? It is much faster than using Interop?
TRIED AND TESTED
private void btnSearch_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection MyCon ;
System.Data.DataSet DtSet ;
System.Data.OleDb.OleDbDataAdapter MyCommand ;
//~~> Replace this with relevant file path
MyCon = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Sample.xlsx;Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\"");
//~~> Replace this with the relevant sheet name
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyCon);
MyCommand.TableMappings.Add("Table", "MyTable");
DtSet = new System.Data.DataSet();
//~~> Fill Dataset
MyCommand.Fill(DtSet);
//~~> Set Source
dataGridView1.DataSource = DtSet.Tables[0];
MyCon.Close();
}
This worked for me ...........
Browses your local folder , picks up the excel ,displays in grid view.
Using oledb is what i suggest
private void OpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog openfiledialog1 = new OpenFileDialog();
if (openfiledialog1.ShowDialog()==System.Windows.Forms.DialogResult.OK)
{
this.textBox_path.Text = openfiledialog1.FileName;
}
}
private void LoadExcel_Click(object sender, EventArgs e)
{
//string pathConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+textBox_path.Text+";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
string pathConn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + textBox_path.Text + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";
OleDbConnection conn = new OleDbConnection(pathConn);
conn.Open();
OleDbDataAdapter mydataadapter = new OleDbDataAdapter("Select * from ["+textBox_sheet.Text+"$]", conn);
DataTable dt = new DataTable();
mydataadapter.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();
}